"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GitService = void 0;
var simple_git_1 = require("simple-git");
var uid_1 = require("uid");
var fs = require("fs");
var mkdirp = require("mkdirp");
var child_process_1 = require("child_process");
var path = require("path");
var os = require("os");
function localExec(cmd) {
    return new Promise(function (resolve, reject) {
        (0, child_process_1.exec)(cmd, { maxBuffer: 10 * 1024 * 1024 }, function (err, stdout, stderr) {
            console.log('err', err);
            if (err) {
                reject(err);
                return;
            }
            // console.log('stdout', stdout)
            resolve(stdout);
        });
    });
}
// import * as sqlite3 from 'sqlite3'
// import moment = require("moment");
// import * as cp from 'child-process'
// const cp = require('child-process');
// console.log('cp', cp)
// var exec = require('child-process-promise').exec;
// const client = sqlite3.verbose()
// const db = new client.Database(path.resolve(__dirname, 'db/tester.db'))
var g_gis = {};
function objectSet(obj) {
    var newObj = {};
    for (var key in obj) {
        if (obj[key] != undefined) {
            newObj[key] = obj[key];
        }
    }
    return newObj;
}
var USER_HOME = process.env.HOME || process.env.USERPROFILE;
var yunserFolder = path.resolve(USER_HOME, '.yunser'); // TODO package，npm install cmd-core
if (!fs.existsSync(yunserFolder)) {
    // console.log('创建目录')
    fs.mkdirSync(yunserFolder);
}
var appFolder = path.resolve(yunserFolder, 'dms-cli'); // TODO package，npm install cmd-core
if (!fs.existsSync(appFolder)) {
    fs.mkdirSync(appFolder);
}
var gitDbFilePath = path.resolve(appFolder, 'git.projects.json');
if (!fs.existsSync(gitDbFilePath)) {
    // console.log('创建目录')
    // fs.mkdirSync(yunserFolder)
    fs.writeFileSync(gitDbFilePath, '[]', 'utf8');
}
var gitSettingFilePath = path.resolve(appFolder, 'git.settings.json');
if (!fs.existsSync(gitSettingFilePath)) {
    // console.log('创建目录')
    // fs.mkdirSync(yunserFolder)
    fs.writeFileSync(gitSettingFilePath, '{}', 'utf8');
}
var folderPath = '/Users/yunser/app/dms-new';
var GitService = /** @class */ (function () {
    function GitService() {
    }
    GitService.prototype.home = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, 'git home'];
            });
        });
    };
    GitService.prototype.version = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _a = {};
                        return [4 /*yield*/, (0, simple_git_1.simpleGit)().version()];
                    case 1: return [2 /*return*/, (_a.version = _b.sent(),
                            _a)];
                }
            });
        });
    };
    GitService.prototype.projectInfo = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath;
            return __generator(this, function (_a) {
                projectPath = body.projectPath;
                return [2 /*return*/, {
                        name: 'dms-new',
                        filePath: folderPath
                    }];
            });
        });
    };
    GitService.prototype.commit = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, message, _a, amend, _b, pushRemote, remoteName, branchName, opts, git, commands, ret;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        projectPath = body.projectPath, message = body.message, _a = body.amend, amend = _a === void 0 ? false : _a, _b = body.pushRemote, pushRemote = _b === void 0 ? false : _b, remoteName = body.remoteName, branchName = body.branchName;
                        opts = {};
                        if (amend) {
                            opts['--amend'] = true;
                        }
                        return [4 /*yield*/, this.getClient(projectPath)
                            // await git.commit(message, [], opts)
                            // return {
                            //     commands: [
                            //         {
                            //             id: uid(32),
                            //             command: `git commit -m '${message}'`,
                            //         }
                            //     ]
                            // }
                        ];
                    case 1:
                        git = _c.sent();
                        commands = ['commit', '-m', message];
                        if (amend) {
                            commands.push('--amend');
                        }
                        return [4 /*yield*/, this._command(git, commands)];
                    case 2:
                        ret = _c.sent();
                        if (!pushRemote) return [3 /*break*/, 4];
                        return [4 /*yield*/, this._command(git, ['push', '-v', remoteName, "refs/heads/".concat(branchName, ":refs/heads/").concat(branchName)])];
                    case 3:
                        _c.sent();
                        _c.label = 4;
                    case 4: return [2 /*return*/, ret];
                }
            });
        });
    };
    GitService.prototype.reset = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, files, git;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, files = body.files;
                        return [4 /*yield*/, this.getClient(projectPath)
                            // await git.reset(ResetMode.MIXED, files)
                            // return {}
                        ];
                    case 1:
                        git = _a.sent();
                        return [4 /*yield*/, this._command(git, __spreadArray(['reset', 'HEAD'], files, true))];
                    case 2: 
                    // await git.reset(ResetMode.MIXED, files)
                    // return {}
                    return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    GitService.prototype.fileDiscard = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, filePath, type, line, lineContent, _filePath, content, lines;
            return __generator(this, function (_a) {
                projectPath = body.projectPath, filePath = body.filePath, type = body.type, line = body.line, lineContent = body.lineContent;
                _filePath = path.resolve(projectPath, filePath);
                content = fs.readFileSync(_filePath, 'utf-8');
                lines = content.split('\n');
                if (type == 'added') {
                    // TODO hack LF CRLF
                    if (lines[line].trim() != lineContent.trim()) {
                        throw new Error('check content fail');
                    }
                    lines.splice(line, 1);
                }
                else if (type == 'deleted') {
                    lines.splice(line + 1, 0, lineContent);
                }
                else {
                    throw new Error('type is error');
                }
                fs.writeFileSync(_filePath, lines.join('\n'));
                return [2 /*return*/];
            });
        });
    };
    GitService.prototype.add = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, files, git;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, files = body.files;
                        return [4 /*yield*/, this.getClient(projectPath)
                            // await git.add(files)
                        ];
                    case 1:
                        git = _a.sent();
                        return [4 /*yield*/, this._command(git, __spreadArray(['add'], files, true))];
                    case 2: 
                    // await git.add(files)
                    return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    GitService.prototype._command = function (git, commands) {
        return __awaiter(this, void 0, void 0, function () {
            var res;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, git.raw(commands)];
                    case 1:
                        res = _a.sent();
                        return [2 /*return*/, {
                                commands: [
                                    {
                                        id: (0, uid_1.uid)(32),
                                        command: 'git ' + commands.join(' '),
                                        res: res,
                                    }
                                ]
                            }];
                }
            });
        });
    };
    GitService.prototype.diff = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, file, cached, git, params, diff;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, file = body.file, cached = body.cached;
                        return [4 /*yield*/, this.getClient(projectPath)
                            // const diff = await git.diffSummary(file)
                        ];
                    case 1:
                        git = _a.sent();
                        if (cached) {
                            params = ['--cached', '--', file];
                        }
                        else {
                            params = ['--', file];
                        }
                        return [4 /*yield*/, git.diff(params)
                            // console.log('diff', diff)
                        ];
                    case 2:
                        diff = _a.sent();
                        // console.log('diff', diff)
                        return [2 /*return*/, {
                                commands: [
                                    {
                                        id: (0, uid_1.uid)(32),
                                        command: 'git diff ' + params.join(' '),
                                    }
                                ],
                                content: diff,
                            }];
                }
            });
        });
    };
    GitService.prototype.remote = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, files, git;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, files = body.files;
                        return [4 /*yield*/, this.getClient(projectPath)];
                    case 1:
                        git = _a.sent();
                        return [4 /*yield*/, git.getRemotes(true)];
                    case 2: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    GitService.prototype.status = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, git, status, content, list, findIndex, fProject;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath;
                        return [4 /*yield*/, this.getClient(projectPath)];
                    case 1:
                        git = _a.sent();
                        return [4 /*yield*/, git.status()
                            // {
                            //     not_added: [],
                            //     conflicted: [],
                            //     created: [ 'b.txt' ],
                            //     deleted: [ 'a.txt' ],
                            //     ignored: undefined,
                            //     modified: [ 'README.md' ],
                            //     renamed: [],
                            //     files: [
                            //       FileStatusSummary {
                            //         path: 'README.md',
                            //         index: ' ',
                            //         working_dir: 'M'
                            //       },
                            //       FileStatusSummary { path: 'a.txt', index: ' ', working_dir: 'D' },
                            //       FileStatusSummary { path: 'b.txt', index: 'A', working_dir: ' ' }
                            //     ],
                            //     staged: [ 'b.txt' ],
                            //     ahead: 0,
                            //     behind: 0,
                            //     current: 'master',
                            //     tracking: null,
                            //     detached: false,
                            //     isClean: [Function (anonymous)]
                            //   }
                            // 更新列表修改信息
                        ];
                    case 2:
                        status = _a.sent();
                        content = fs.readFileSync(gitDbFilePath, 'utf-8') || '[]';
                        list = JSON.parse(content);
                        findIndex = list.findIndex(function (p) { return p.path == projectPath; });
                        // console.log('findIndex', findIndex)
                        if (findIndex != -1) {
                            fProject = list[findIndex];
                            // console.log('fProject', fProject)
                            if (fProject.changes != status.files.length) {
                                list[findIndex].changes = status.files.length;
                                fs.writeFileSync(gitDbFilePath, JSON.stringify(list, null, 4), 'utf-8');
                            }
                        }
                        return [2 /*return*/, {
                                status: status,
                            }];
                }
            });
        });
    };
    GitService.prototype.branchRename = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, oldBranchName, newBranchName, git, commands;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, oldBranchName = body.oldBranchName, newBranchName = body.newBranchName;
                        return [4 /*yield*/, this.getClient(projectPath)];
                    case 1:
                        git = _a.sent();
                        commands = ['branch', '-m', oldBranchName, newBranchName];
                        return [4 /*yield*/, this._command(git, commands)];
                    case 2: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    GitService.prototype.branchDelete = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, name, _a, force, _b, deleteRemote, git, idx, after, remoteName, remoteBranchName, commands, remoteName, commands;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        projectPath = body.projectPath, name = body.name, _a = body.force, force = _a === void 0 ? false : _a, _b = body.deleteRemote, deleteRemote = _b === void 0 ? false : _b;
                        return [4 /*yield*/, this.getClient(projectPath)];
                    case 1:
                        git = _c.sent();
                        if (!name.startsWith('remotes/')) return [3 /*break*/, 3];
                        idx = name.indexOf('/');
                        after = name.substring(idx + 1);
                        console.log('after', after);
                        idx = after.indexOf('/');
                        remoteName = after.substring(0, idx);
                        remoteBranchName = after.substring(idx + 1);
                        commands = ['push', remoteName, '--delete', remoteBranchName];
                        console.log('commands', commands);
                        return [4 /*yield*/, this._command(git, commands)];
                    case 2: return [2 /*return*/, _c.sent()];
                    case 3:
                        if (!deleteRemote) return [3 /*break*/, 5];
                        remoteName = 'origin';
                        commands = ['push', remoteName, '--delete', name];
                        console.log('commands', commands);
                        return [4 /*yield*/, this._command(git, commands)];
                    case 4:
                        _c.sent();
                        _c.label = 5;
                    case 5: return [4 /*yield*/, git.deleteLocalBranch(name, force)
                        // console.log('branch', branch)
                    ];
                    case 6:
                        _c.sent();
                        // console.log('branch', branch)
                        return [2 /*return*/, {
                                commands: [
                                    {
                                        id: (0, uid_1.uid)(32),
                                        command: "git branch -".concat(force ? 'D' : 'd', " ").concat(name),
                                    }
                                ],
                            }];
                }
            });
        });
    };
    GitService.prototype.branchCreate = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, name, commit, remoteBranch, git, commands, createBranchCommands, checkoutCommands;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, name = body.name, commit = body.commit, remoteBranch = body.remoteBranch;
                        return [4 /*yield*/, this.getClient(projectPath)];
                    case 1:
                        git = _a.sent();
                        if (!remoteBranch) return [3 /*break*/, 3];
                        commands = ['checkout', '-b', name, remoteBranch];
                        console.log('commandsc', commands);
                        return [4 /*yield*/, this._command(git, commands)];
                    case 2: return [2 /*return*/, _a.sent()];
                    case 3:
                        createBranchCommands = ['checkout', '-b', name];
                        if (commit) {
                            createBranchCommands.push(commit);
                        }
                        return [4 /*yield*/, this._command(git, createBranchCommands)
                            // console.log('branch', branch)
                        ];
                    case 4:
                        _a.sent();
                        checkoutCommands = ['checkout', name];
                        return [4 /*yield*/, this._command(git, checkoutCommands)];
                    case 5:
                        _a.sent();
                        return [2 /*return*/, {
                                commands: [
                                    {
                                        id: (0, uid_1.uid)(32),
                                        command: "git ".concat(createBranchCommands.join(' ')),
                                    },
                                    {
                                        id: (0, uid_1.uid)(32),
                                        command: "git ".concat(checkoutCommands.join(' ')),
                                    },
                                ],
                            }];
                }
            });
        });
    };
    GitService.prototype.branchList = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, git, branch, content, list, findIndex, fProject, commits, log, err_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath;
                        return [4 /*yield*/, this.getClient(projectPath)];
                    case 1:
                        git = _a.sent();
                        return [4 /*yield*/, git.branch()
                            // console.log('branch', branch)
                            // {
                            //     all: [ 'master' ],
                            //     branches: {
                            //       master: {
                            //         current: true,
                            //         linkedWorkTree: false,
                            //         name: 'master',
                            //         commit: '2c838b2',
                            //         label: 'first commit!'
                            //       }
                            //     },
                            //     current: 'master',
                            //     detached: false
                            //   }
                            // 更新列表分支信息
                        ];
                    case 2:
                        branch = _a.sent();
                        content = fs.readFileSync(gitDbFilePath, 'utf-8') || '[]';
                        list = JSON.parse(content);
                        findIndex = list.findIndex(function (p) { return p.path == projectPath; });
                        // console.log('findIndex', findIndex)
                        if (findIndex != -1) {
                            fProject = list[findIndex];
                            // console.log('fProject', fProject)
                            if (fProject.branch != branch.current) {
                                list[findIndex].branch = branch.current;
                                fs.writeFileSync(gitDbFilePath, JSON.stringify(list, null, 4), 'utf-8');
                            }
                        }
                        commits = [];
                        _a.label = 3;
                    case 3:
                        _a.trys.push([3, 5, , 6]);
                        return [4 /*yield*/, git.log({})
                            // console.log('log', log)
                        ];
                    case 4:
                        log = _a.sent();
                        // console.log('log', log)
                        commits = log.all;
                        return [3 /*break*/, 6];
                    case 5:
                        err_1 = _a.sent();
                        if (err_1.message && err_1.message.includes('does not have any commits yet')) {
                        }
                        else {
                            throw err_1;
                        }
                        return [3 /*break*/, 6];
                    case 6: return [2 /*return*/, {
                            current: branch.current,
                            list: branch.all.map(function (branchName) {
                                var _branch = branch.branches[branchName];
                                var fCommit = commits.find(function (item) { return item.hash.startsWith(_branch.commit); });
                                return __assign(__assign({}, _branch), { commitObj: fCommit || null });
                            })
                        }];
                }
            });
        });
    };
    GitService.prototype.projectList = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var content, list;
            return __generator(this, function (_a) {
                content = fs.readFileSync(gitDbFilePath, 'utf-8') || '[]';
                list = JSON.parse(content);
                return [2 /*return*/, {
                        list: list,
                    }];
            });
        });
    };
    GitService.prototype.remoteCreate = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, name, url, git;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, name = body.name, url = body.url;
                        return [4 /*yield*/, this.getClient(projectPath)];
                    case 1:
                        git = _a.sent();
                        return [4 /*yield*/, git.addRemote(name, url)];
                    case 2:
                        _a.sent();
                        return [2 /*return*/, {
                                commands: [
                                    {
                                        id: (0, uid_1.uid)(32),
                                        command: "git remote add ".concat(name, " ").concat(url),
                                    }
                                ],
                            }];
                }
            });
        });
    };
    GitService.prototype.tagPush = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, remoteName, tag, mode, git, commands;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, remoteName = body.remoteName, tag = body.tag, mode = body.mode;
                        return [4 /*yield*/, this.getClient(projectPath)
                            // await git.push(remoteName, branchName)
                            // git push origin master
                            // git push origin master:master
                            // push -v origin refs/heads/master:refs/heads/master 
                        ];
                    case 1:
                        git = _a.sent();
                        if (tag) {
                            commands = ['push', '-v', remoteName, "refs/tags/".concat(tag)];
                        }
                        else {
                            commands = ['push', '-v', remoteName, '--tags'];
                        }
                        return [4 /*yield*/, this._command(git, commands)];
                    case 2: 
                    // if (mode == 'force') {
                    //     commands.push('--force')
                    // }
                    // console.log('commands', commands)
                    // return await git.raw(commands)
                    return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    GitService.prototype.push = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, remoteName, branchName, mode, git, commands;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, remoteName = body.remoteName, branchName = body.branchName, mode = body.mode;
                        return [4 /*yield*/, this.getClient(projectPath)
                            // await git.push(remoteName, branchName)
                            // git push origin master
                            // git push origin master:master
                            // push -v origin refs/heads/master:refs/heads/master 
                        ];
                    case 1:
                        git = _a.sent();
                        commands = ['push', '-v', remoteName, "refs/heads/".concat(branchName, ":refs/heads/").concat(branchName)];
                        if (mode == 'force') {
                            commands.push('--force');
                        }
                        return [4 /*yield*/, this._command(git, commands)];
                    case 2: 
                    // console.log('commands', commands)
                    // return await git.raw(commands)
                    return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    GitService.prototype.pull = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, remoteName, branchName, git;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, remoteName = body.remoteName, branchName = body.branchName;
                        return [4 /*yield*/, this.getClient(projectPath)
                            // 拉取全部
                            // await git.pull()
                        ];
                    case 1:
                        git = _a.sent();
                        // 拉取全部
                        // await git.pull()
                        return [4 /*yield*/, git.pull(remoteName, branchName)];
                    case 2:
                        // 拉取全部
                        // await git.pull()
                        _a.sent();
                        return [2 /*return*/, {
                                commands: [
                                    {
                                        id: (0, uid_1.uid)(32),
                                        command: "git pull ".concat(remoteName, " ").concat(branchName),
                                    }
                                ],
                            }];
                }
            });
        });
    };
    GitService.prototype.show = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, remoteName, commit, git, params, res, arr, files, idx, line, _a, status_1, name_1;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        projectPath = body.projectPath, remoteName = body.remoteName, commit = body.commit;
                        return [4 /*yield*/, this.getClient(projectPath)
                            // const params = ['show', commit, '--stat', '--name-only']
                        ];
                    case 1:
                        git = _b.sent();
                        params = ['show', commit, '--stat', '--name-status'];
                        return [4 /*yield*/, git.raw(params)
                            // console.log('show/res', res)
                            // console.log('show/res/end')
                        ];
                    case 2:
                        res = _b.sent();
                        arr = res.split('\n');
                        files = [];
                        for (idx = arr.length - 2; idx >= 0; idx--) {
                            line = arr[idx];
                            if (line == '') {
                                break;
                            }
                            if (!line.includes('changed')) {
                                _a = line.split(/\s+/), status_1 = _a[0], name_1 = _a[1];
                                files.push({
                                    status: status_1.trim(),
                                    name: name_1.trim(),
                                });
                            }
                        }
                        // console.log('files', files)
                        return [2 /*return*/, {
                                files: files,
                                res: res,
                                commands: [
                                    {
                                        id: (0, uid_1.uid)(32),
                                        command: 'git show ' + params.join(' '),
                                    }
                                ],
                            }];
                }
            });
        });
    };
    GitService.prototype.commitFileChanged = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, commit, filePath, git, params, res;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, commit = body.commit, filePath = body.filePath;
                        return [4 /*yield*/, this.getClient(projectPath)
                            // console.log('ppp', commit, filePath)
                        ];
                    case 1:
                        git = _a.sent();
                        params = [commit, '--', filePath];
                        return [4 /*yield*/, git.show(params)
                            // console.log('res', res)
                            // await git.checkoutLocalBranch(branchName)
                            // const cmd = `cd ${projectPath} && git show ${commit} ${filePath}`
                            // console.log('cmd', cmd)
                            // exec(cmd)
                            //     .then(function (result) {
                            //         console.log('result', result)
                            //         var stdout = result.stdout;
                            //         var stderr = result.stderr;
                            //         console.log('stdout: ', stdout);
                            //         console.log('stderr: ', stderr);
                            //     })
                            //     .catch(function (err) {
                            //         console.error('ERROR: ', err);
                            //     });
                            // const child = cp.exec(, function(err, stdout, stderr){
                            //     console.log('?', err, stdout, stderr);
                            // })
                        ];
                    case 2:
                        res = _a.sent();
                        // console.log('res', res)
                        // await git.checkoutLocalBranch(branchName)
                        // const cmd = `cd ${projectPath} && git show ${commit} ${filePath}`
                        // console.log('cmd', cmd)
                        // exec(cmd)
                        //     .then(function (result) {
                        //         console.log('result', result)
                        //         var stdout = result.stdout;
                        //         var stderr = result.stderr;
                        //         console.log('stdout: ', stdout);
                        //         console.log('stderr: ', stderr);
                        //     })
                        //     .catch(function (err) {
                        //         console.error('ERROR: ', err);
                        //     });
                        // const child = cp.exec(, function(err, stdout, stderr){
                        //     console.log('?', err, stdout, stderr);
                        // })
                        return [2 /*return*/, {
                                res: res,
                                commands: [
                                    {
                                        id: (0, uid_1.uid)(32),
                                        command: 'git show ' + params.join(' '),
                                    }
                                ],
                                // res: '',
                            }];
                }
            });
        });
    };
    GitService.prototype.cat = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, filePath, sizeLimit, fullPath, stat, content;
            return __generator(this, function (_a) {
                projectPath = body.projectPath, filePath = body.filePath, sizeLimit = body.sizeLimit;
                fullPath = path.join(projectPath, filePath);
                if (sizeLimit) {
                    stat = fs.statSync(fullPath);
                    // console.log('stat', stat)
                    if (stat.size >= sizeLimit) {
                        throw new Error('file too large!');
                    }
                }
                content = fs.readFileSync(fullPath, 'utf-8');
                return [2 /*return*/, {
                        content: content,
                        commands: [
                            {
                                id: (0, uid_1.uid)(32),
                                command: "cat ".concat(filePath),
                            }
                        ],
                    }];
            });
        });
    };
    GitService.prototype.getInfo = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, {
                        pathSeparator: path.sep,
                    }];
            });
        });
    };
    GitService.prototype.getSshPublicKey = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var git, stdout;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        git = (0, simple_git_1.simpleGit)();
                        return [4 /*yield*/, localExec('cat ~/.ssh/id_rsa.pub')];
                    case 1:
                        stdout = _a.sent();
                        return [2 /*return*/, {
                                sshRsa: stdout,
                            }];
                }
            });
        });
    };
    GitService.prototype.getGlobalConfig = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var git, userName, userEmail;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        git = (0, simple_git_1.simpleGit)();
                        return [4 /*yield*/, git.getConfig('user.name')];
                    case 1:
                        userName = _a.sent();
                        return [4 /*yield*/, git.getConfig('user.email')];
                    case 2:
                        userEmail = _a.sent();
                        return [2 /*return*/, {
                                config: {
                                    user: {
                                        name: userName.value,
                                        email: userEmail.value,
                                    }
                                },
                            }];
                }
            });
        });
    };
    GitService.prototype.setGlobalConfig = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, user, name, email, git;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, user = body.user;
                        name = user.name, email = user.email;
                        return [4 /*yield*/, this.getClient(projectPath)];
                    case 1:
                        git = _a.sent();
                        return [4 /*yield*/, git.addConfig('user.name', name, false, simple_git_1.GitConfigScope.global)];
                    case 2:
                        _a.sent();
                        return [4 /*yield*/, git.addConfig('user.email', email, false, simple_git_1.GitConfigScope.global)];
                    case 3:
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    GitService.prototype.getConfig = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, git, userName, userEmail;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath;
                        return [4 /*yield*/, this.getClient(projectPath)];
                    case 1:
                        git = _a.sent();
                        return [4 /*yield*/, git.getConfig('user.name')];
                    case 2:
                        userName = _a.sent();
                        return [4 /*yield*/, git.getConfig('user.email')];
                    case 3:
                        userEmail = _a.sent();
                        return [2 /*return*/, {
                                config: {
                                    user: {
                                        name: userName.value,
                                        email: userEmail.value,
                                    }
                                },
                            }];
                }
            });
        });
    };
    GitService.prototype.setConfig = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, user, name, email, git;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, user = body.user;
                        name = user.name, email = user.email;
                        return [4 /*yield*/, this.getClient(projectPath)];
                    case 1:
                        git = _a.sent();
                        return [4 /*yield*/, git.addConfig('user.name', name, false, simple_git_1.GitConfigScope.local)];
                    case 2:
                        _a.sent();
                        return [4 /*yield*/, git.addConfig('user.email', email, false, simple_git_1.GitConfigScope.local)];
                    case 3:
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    GitService.prototype.checkout = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, remoteName, branchName, git, res;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, remoteName = body.remoteName, branchName = body.branchName;
                        return [4 /*yield*/, this.getClient(projectPath)];
                    case 1:
                        git = _a.sent();
                        return [4 /*yield*/, git.checkout(branchName)
                            // console.log('res', res)
                            // await git.checkoutLocalBranch(branchName)
                        ];
                    case 2:
                        res = _a.sent();
                        // console.log('res', res)
                        // await git.checkoutLocalBranch(branchName)
                        return [2 /*return*/, {
                                commands: [
                                    {
                                        id: (0, uid_1.uid)(32),
                                        command: "git checkout ".concat(branchName),
                                    }
                                ],
                            }];
                }
            });
        });
    };
    GitService.prototype.cherryPick = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, commit, branch, git;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, commit = body.commit, branch = body.branch;
                        return [4 /*yield*/, this.getClient(projectPath)];
                    case 1:
                        git = _a.sent();
                        return [4 /*yield*/, git.checkout(branch)
                            // console.log('res', res)
                            // await git.checkoutLocalBranch(branchName)
                            // return {
                            //     commands: [
                            //         {
                            //             id: uid(32),
                            //             command: `git checkout ${branchName}`,
                            //         }
                            //     ],
                            // }
                        ];
                    case 2:
                        _a.sent();
                        return [4 /*yield*/, this._command(git, ['cherry-pick', commit])];
                    case 3: 
                    // console.log('res', res)
                    // await git.checkoutLocalBranch(branchName)
                    // return {
                    //     commands: [
                    //         {
                    //             id: uid(32),
                    //             command: `git checkout ${branchName}`,
                    //         }
                    //     ],
                    // }
                    return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    GitService.prototype.checkoutFile = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, filePath, git;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, filePath = body.filePath;
                        return [4 /*yield*/, this.getClient(projectPath)
                            // const res = await git.checkout(['--', filePath])
                            // console.log('res', res)
                        ];
                    case 1:
                        git = _a.sent();
                        return [4 /*yield*/, this._command(git, ['checkout', '--', filePath])];
                    case 2: 
                    // const res = await git.checkout(['--', filePath])
                    // console.log('res', res)
                    return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    GitService.prototype.merge = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, fromBranch, toBranch, _a, pushRemote, git, res, commands;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        projectPath = body.projectPath, fromBranch = body.fromBranch, toBranch = body.toBranch, _a = body.pushRemote, pushRemote = _a === void 0 ? false : _a;
                        return [4 /*yield*/, this.getClient(projectPath)
                            // const res = await git.merge(fromBranch)
                        ];
                    case 1:
                        git = _b.sent();
                        return [4 /*yield*/, git.mergeFromTo(fromBranch, toBranch)
                            // console.log('res', res)
                            // await git.checkoutLocalBranch(branchName)
                        ];
                    case 2:
                        res = _b.sent();
                        if (!pushRemote) return [3 /*break*/, 4];
                        commands = ['push', '-v', 'origin', "refs/heads/".concat(toBranch)];
                        return [4 /*yield*/, this._command(git, commands)];
                    case 3:
                        _b.sent();
                        _b.label = 4;
                    case 4: return [2 /*return*/, {
                            commands: [
                                {
                                    id: (0, uid_1.uid)(32),
                                    command: "git merge ".concat(fromBranch),
                                }
                            ],
                        }];
                }
            });
        });
    };
    GitService.prototype.fetch = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, remoteName, branchName, git, fetch;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, remoteName = body.remoteName, branchName = body.branchName;
                        return [4 /*yield*/, this.getClient(projectPath)];
                    case 1:
                        git = _a.sent();
                        return [4 /*yield*/, git.fetch(remoteName)
                            // console.log('fetch', fetch)
                        ];
                    case 2:
                        fetch = _a.sent();
                        // console.log('fetch', fetch)
                        return [2 /*return*/, {
                                fetch: fetch,
                            }];
                }
            });
        });
    };
    GitService.prototype.projectCreate = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var url, name, path, _a, init, git, content, list;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        url = body.url, name = body.name, path = body.path, _a = body.init, init = _a === void 0 ? false : _a;
                        if (!url) return [3 /*break*/, 2];
                        // console.log('start clone')
                        return [4 /*yield*/, (0, simple_git_1.simpleGit)().clone(url, path)
                            // .then(() => console.log('finished'))
                            // .catch((err) => console.error('failed: ', err));
                        ];
                    case 1:
                        // console.log('start clone')
                        _b.sent();
                        _b.label = 2;
                    case 2:
                        if (!init) return [3 /*break*/, 5];
                        if (!!fs.existsSync(path)) return [3 /*break*/, 4];
                        return [4 /*yield*/, mkdirp(path)];
                    case 3:
                        _b.sent();
                        _b.label = 4;
                    case 4:
                        git = (0, simple_git_1.simpleGit)(path, { binary: 'git' });
                        git.init();
                        _b.label = 5;
                    case 5:
                        content = fs.readFileSync(gitDbFilePath, 'utf-8') || '[]';
                        list = JSON.parse(content);
                        list.unshift({
                            id: (0, uid_1.uid)(32),
                            name: name,
                            path: path,
                        });
                        fs.writeFileSync(gitDbFilePath, JSON.stringify(list, null, 4), 'utf-8');
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    GitService.prototype.projectUpdate = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var id, data, name, isFavorite, favoriteTime, content, list, findIndex, fProject;
            return __generator(this, function (_a) {
                id = body.id, data = body.data;
                name = data.name, isFavorite = data.isFavorite, favoriteTime = data.favoriteTime;
                content = fs.readFileSync(gitDbFilePath, 'utf-8') || '[]';
                list = JSON.parse(content);
                findIndex = list.findIndex(function (p) { return p.id == id; });
                // console.log('findIndex', findIndex)
                if (findIndex != -1) {
                    fProject = list[findIndex];
                    list[findIndex] = __assign(__assign({}, list[findIndex]), objectSet({
                        name: name,
                        isFavorite: isFavorite,
                        favoriteTime: favoriteTime,
                    }));
                    // list[findIndex].name = name
                    // name, isFavorite
                    // console.log('fProject', fProject)
                    fs.writeFileSync(gitDbFilePath, JSON.stringify(list, null, 4), 'utf-8');
                }
                return [2 /*return*/, {}];
            });
        });
    };
    GitService.prototype.projectDelete = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var id, content, list, newProjects;
            return __generator(this, function (_a) {
                id = body.id;
                content = fs.readFileSync(gitDbFilePath, 'utf-8') || '[]';
                list = JSON.parse(content);
                newProjects = list.filter(function (item) { return item.id != id; });
                fs.writeFileSync(gitDbFilePath, JSON.stringify(newProjects, null, 4), 'utf-8');
                return [2 /*return*/, {}];
            });
        });
    };
    GitService.prototype.tagList = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, git, tag;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath;
                        return [4 /*yield*/, this.getClient(projectPath)];
                    case 1:
                        git = _a.sent();
                        return [4 /*yield*/, git.tags()
                            // console.log('log', log)
                            // console.log('removeList')
                            // git.listRemote(['--tags'], console.log)
                            // git.listRemote(['--heads'], console.log)
                        ];
                    case 2:
                        tag = _a.sent();
                        // console.log('log', log)
                        // console.log('removeList')
                        // git.listRemote(['--tags'], console.log)
                        // git.listRemote(['--heads'], console.log)
                        return [2 /*return*/, {
                                list: tag.all.map(function (name) {
                                    return {
                                        name: name,
                                    };
                                })
                            }];
                }
            });
        });
    };
    GitService.prototype.tagRemoteList = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, remoteName, git, tagsRes, list;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, remoteName = body.remoteName;
                        return [4 /*yield*/, this.getClient(projectPath)
                            // git.listRemote(['--tags'], console.log)
                        ];
                    case 1:
                        git = _a.sent();
                        return [4 /*yield*/, git.raw(['ls-remote', '--tags', remoteName])];
                    case 2:
                        tagsRes = _a.sent();
                        console.log('tagsRes', tagsRes);
                        list = tagsRes.split('\n')
                            .filter(function (item) { return item; })
                            .map(function (item) {
                            var arr = item.split('\t');
                            return {
                                commit: arr[0],
                                name: arr[1],
                            };
                        });
                        // console.log('list', list)
                        return [2 /*return*/, {
                                list: list,
                            }];
                }
            });
        });
    };
    GitService.prototype.tagDelete = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, name, _a, deleteRemote, git;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        projectPath = body.projectPath, name = body.name, _a = body.deleteRemote, deleteRemote = _a === void 0 ? false : _a;
                        return [4 /*yield*/, this.getClient(projectPath)];
                    case 1:
                        git = _b.sent();
                        if (!deleteRemote) return [3 /*break*/, 3];
                        return [4 /*yield*/, this._command(git, ['push', 'origin', ":refs/tags/".concat(name)])];
                    case 2:
                        _b.sent();
                        _b.label = 3;
                    case 3: return [4 /*yield*/, this._command(git, ['tag', '--delete', name])];
                    case 4: return [2 /*return*/, _b.sent()];
                }
            });
        });
    };
    GitService.prototype.tagDeleteRemote = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, remoteName, name, git, commands;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, remoteName = body.remoteName, name = body.name;
                        return [4 /*yield*/, this.getClient(projectPath)
                            // git push origin :refs/tags/prod1.0
                        ];
                    case 1:
                        git = _a.sent();
                        commands = ['push', remoteName, ":".concat(name)];
                        console.log('commands', commands);
                        return [4 /*yield*/, this._command(git, commands)];
                    case 2: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    GitService.prototype.command = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, _a, commands, git;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        projectPath = body.projectPath, _a = body.commands, commands = _a === void 0 ? [] : _a;
                        return [4 /*yield*/, this.getClient(projectPath)
                            // console.log('cmd', commands.join(' '))
                            // await git.raw(commands)
                        ];
                    case 1:
                        git = _b.sent();
                        return [4 /*yield*/, this._command(git, commands)
                            // console.log('log', log)
                            // return {}
                        ];
                    case 2: 
                    // console.log('cmd', commands.join(' '))
                    // await git.raw(commands)
                    return [2 /*return*/, _b.sent()
                        // console.log('log', log)
                        // return {}
                    ];
                }
            });
        });
    };
    GitService.prototype.deleteFile = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, filePath;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, filePath = body.filePath;
                        return [4 /*yield*/, fs.unlinkSync(path.join(projectPath, filePath))];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    GitService.prototype.userConfig = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var content;
            return __generator(this, function (_a) {
                content = fs.readFileSync(gitSettingFilePath, 'utf-8');
                return [2 /*return*/, __assign({ userHome: USER_HOME, fileSeparator: path.sep }, JSON.parse(content))];
            });
        });
    };
    GitService.prototype.userConfigUpdate = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var content, configs;
            return __generator(this, function (_a) {
                content = fs.readFileSync(gitSettingFilePath, 'utf-8');
                configs = JSON.parse(content);
                fs.writeFileSync(gitSettingFilePath, JSON.stringify(__assign(__assign({}, configs), { defaultClonePath: body.defaultClonePath }), null, 4), 'utf-8');
                return [2 /*return*/, {}];
            });
        });
    };
    GitService.prototype.fileContent = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, commit, file, git, res;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, commit = body.commit, file = body.file;
                        return [4 /*yield*/, this.getClient(projectPath)
                            // const tag = await git.addTag(name)
                            // console.log('log', log)
                        ];
                    case 1:
                        git = _a.sent();
                        return [4 /*yield*/, git.raw(['show', "".concat(commit, ":").concat(file)])];
                    case 2:
                        res = _a.sent();
                        console.log('res', res);
                        return [2 /*return*/, {
                                content: res,
                            }];
                }
            });
        });
    };
    GitService.prototype.tagCreate = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, name, commit, pushRemote, git, params, ret, commands;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, name = body.name, commit = body.commit, pushRemote = body.pushRemote;
                        return [4 /*yield*/, this.getClient(projectPath)
                            // const tag = await git.addTag(name)
                            // console.log('log', log)
                        ];
                    case 1:
                        git = _a.sent();
                        params = ['tag', name];
                        if (commit) {
                            params.push(commit);
                        }
                        return [4 /*yield*/, this._command(git, params)];
                    case 2:
                        ret = _a.sent();
                        if (!pushRemote) return [3 /*break*/, 4];
                        commands = ['push', '-v', 'origin', "refs/tags/".concat(name)];
                        return [4 /*yield*/, this._command(git, commands)];
                    case 3:
                        _a.sent();
                        _a.label = 4;
                    case 4: return [2 /*return*/, ret
                        // return {
                        //     commands: [
                        //         {
                        //             command: `git tag ${name}`,
                        //         }
                        //     ],
                        // }
                    ];
                }
            });
        });
    };
    GitService.prototype.graph = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, limit, file, author, git, commands, log, cmd, result;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, limit = body.limit, file = body.file, author = body.author;
                        return [4 /*yield*/, this.getClient(projectPath)
                            // 下面的功能在 Windows 上会报错，故暂不支持 Windows
                        ];
                    case 1:
                        git = _a.sent();
                        // 下面的功能在 Windows 上会报错，故暂不支持 Windows
                        if (os.platform() == 'win32') {
                            return [2 /*return*/, {
                                    result: 'not support in Windows',
                                }];
                        }
                        commands = ["log', '--oneline', '--graph', '--decorate', '--all"];
                        return [4 /*yield*/, git.log({
                                format: '%h|%p|%D|(%cr)|%cn|%s'
                            })];
                    case 2:
                        log = _a.sent();
                        cmd = "cd ".concat(projectPath, " && git log --graph --all | cat");
                        return [4 /*yield*/, localExec(cmd)];
                    case 3:
                        result = _a.sent();
                        return [2 /*return*/, {
                                result: result.substring(0, 20000) + '\n...',
                            }
                            // await this._command(git, commands)
                        ];
                }
            });
        });
    };
    GitService.prototype.commitList = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, limit, file, author, git, commits, opts, log, err_2;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, limit = body.limit, file = body.file, author = body.author;
                        return [4 /*yield*/, this.getClient(projectPath)];
                    case 1:
                        git = _a.sent();
                        commits = [];
                        opts = {
                        // file: 'README.md'
                        };
                        if (limit) {
                            opts.maxCount = limit;
                        }
                        if (file) {
                            opts.file = file;
                        }
                        if (author) {
                            opts.author_email = author;
                        }
                        _a.label = 2;
                    case 2:
                        _a.trys.push([2, 4, , 5]);
                        return [4 /*yield*/, git.log(opts)
                            // console.log('log', log)
                        ];
                    case 3:
                        log = _a.sent();
                        // console.log('log', log)
                        commits = log.all;
                        return [3 /*break*/, 5];
                    case 4:
                        err_2 = _a.sent();
                        if (err_2.message && err_2.message.includes('does not have any commits yet')) {
                        }
                        else {
                            throw err_2;
                        }
                        return [3 /*break*/, 5];
                    case 5: 
                    // {
                    //     all: [
                    //       {
                    //         hash: '489deea0f6bf7e90a7434f4ae22c5e17214bdf5d',
                    //         date: '2022-09-23T19:23:59+08:00',
                    //         message: '「add」b',
                    //         refs: 'HEAD -> master',
                    //         body: '',
                    //         author_name: 'cjhgit',
                    //         author_email: '1418503647@qq.com'
                    //       },
                    //       {
                    //         hash: '2c838b2a6b7550564774fad18e505631fb0c9322',
                    //         date: '2022-09-23T19:01:14+08:00',
                    //         message: 'first commit!',
                    //         refs: '',
                    //         body: '',
                    //         author_name: 'cjhgit',
                    //         author_email: '1418503647@qq.com'
                    //       }
                    //     ],
                    //     latest: {
                    //       hash: '489deea0f6bf7e90a7434f4ae22c5e17214bdf5d',
                    //       date: '2022-09-23T19:23:59+08:00',
                    //       message: '「add」b',
                    //       refs: 'HEAD -> master',
                    //       body: '',
                    //       author_name: 'cjhgit',
                    //       author_email: '1418503647@qq.com'
                    //     },
                    //     total: 2
                    //   }
                    return [2 /*return*/, commits];
                }
            });
        });
    };
    GitService.prototype.getClient = function (projectPath) {
        if (projectPath === void 0) { projectPath = folderPath; }
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                if (!projectPath) {
                    throw new Error('projectPath required');
                }
                if (!g_gis[projectPath]) {
                    g_gis[projectPath] = (0, simple_git_1.simpleGit)(projectPath, { binary: 'git' });
                }
                // const git: SimpleGit = simpleGit(folderPath, { binary: 'git' });
                return [2 /*return*/, g_gis[projectPath]];
            });
        });
    };
    GitService.prototype.stashList = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, git, result, list;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath;
                        return [4 /*yield*/, this.getClient(projectPath)];
                    case 1:
                        git = _a.sent();
                        return [4 /*yield*/, git.stashList()];
                    case 2:
                        result = _a.sent();
                        list = Object.keys(result.all).map(function (idx) {
                            return __assign(__assign({}, result.all[idx]), { index: idx });
                        });
                        return [2 /*return*/, {
                                list: list,
                                total: result.total,
                                latest: result.latest,
                            }];
                }
            });
        });
    };
    GitService.prototype.stashCreate = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, message, git;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, message = body.message;
                        return [4 /*yield*/, this.getClient(projectPath)];
                    case 1:
                        git = _a.sent();
                        git.stash({
                            '--message': message,
                        });
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    GitService.prototype.stashApply = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, index, git, command;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, index = body.index;
                        return [4 /*yield*/, this.getClient(projectPath)];
                    case 1:
                        git = _a.sent();
                        command = ['stash', 'apply', "stash@{".concat(index, "}")];
                        return [4 /*yield*/, this._command(git, command)];
                    case 2: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    GitService.prototype.stashDelete = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, index, git, command;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, index = body.index;
                        return [4 /*yield*/, this.getClient(projectPath)];
                    case 1:
                        git = _a.sent();
                        command = ['stash', 'drop', "stash@{".concat(index, "}")];
                        return [4 /*yield*/, this._command(git, command)];
                    case 2: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    GitService.prototype.stashClear = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, git, command;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath;
                        return [4 /*yield*/, this.getClient(projectPath)];
                    case 1:
                        git = _a.sent();
                        command = ['stash', 'clear'];
                        return [4 /*yield*/, this._command(git, command)];
                    case 2: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    return GitService;
}());
exports.GitService = GitService;
//# sourceMappingURL=git.service.js.map