"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 path = require("path");
// 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.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, opts, git, commands;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        projectPath = body.projectPath, message = body.message, _a = body.amend, amend = _a === void 0 ? false : _a;
                        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 = _b.sent();
                        commands = ['commit', '-m', message];
                        if (amend) {
                            commands.push('--amend');
                        }
                        return [4 /*yield*/, this._command(git, commands)];
                    case 2: return [2 /*return*/, _b.sent()];
                }
            });
        });
    };
    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.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 () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, git.raw(commands)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, {
                                commands: [
                                    {
                                        id: (0, uid_1.uid)(32),
                                        command: 'git ' + commands.join(' '),
                                    }
                                ]
                            }];
                }
            });
        });
    };
    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()];
                    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.branchDelete = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, name, _a, force, git, branch;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        projectPath = body.projectPath, name = body.name, _a = body.force, force = _a === void 0 ? false : _a;
                        return [4 /*yield*/, this.getClient(projectPath)];
                    case 1:
                        git = _b.sent();
                        return [4 /*yield*/, git.deleteLocalBranch(name, force)
                            // console.log('branch', branch)
                        ];
                    case 2:
                        branch = _b.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, git, createBranchCommands, checkoutCommands;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, name = body.name, commit = body.commit;
                        return [4 /*yield*/, this.getClient(projectPath)
                            // const branch = await git.checkoutLocalBranch(name)
                        ];
                    case 1:
                        git = _a.sent();
                        createBranchCommands = ['branch', name];
                        if (commit) {
                            createBranchCommands.push(commit);
                        }
                        return [4 /*yield*/, this._command(git, createBranchCommands)
                            // console.log('branch', branch)
                        ];
                    case 2:
                        _a.sent();
                        checkoutCommands = ['checkout', name];
                        return [4 /*yield*/, this._command(git, checkoutCommands)];
                    case 3:
                        _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;
            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');
                            }
                        }
                        return [2 /*return*/, {
                                current: branch.current,
                                list: branch.all.map(function (branchName) {
                                    return branch.branches[branchName];
                                })
                            }];
                }
            });
        });
    };
    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.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;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, remoteName = body.remoteName, commit = body.commit;
                        return [4 /*yield*/, this.getClient(projectPath)];
                    case 1:
                        git = _a.sent();
                        params = [commit, '--stat'];
                        return [4 /*yield*/, git.show(params)
                            // console.log('show/res', res)
                            // console.log('show/res/end')
                        ];
                    case 2:
                        res = _a.sent();
                        arr = res.split('\n');
                        files = [];
                        for (idx = arr.length - 2; idx >= 0; idx--) {
                            line = arr[idx];
                            if (line == '') {
                                break;
                            }
                            if (!line.includes('changed')) {
                                files.push(line.split('|')[0].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.getConfig = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, remoteName, branchName, git, userNameconfig, userEmailconfig;
            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.getConfig('user.name')];
                    case 2:
                        userNameconfig = _a.sent();
                        return [4 /*yield*/, git.getConfig('user.email')
                            // console.log('res', res)
                            // await git.checkoutLocalBranch(branchName)
                        ];
                    case 3:
                        userEmailconfig = _a.sent();
                        // console.log('res', res)
                        // await git.checkoutLocalBranch(branchName)
                        return [2 /*return*/, {
                                config: {
                                    user: {
                                        name: userNameconfig.value,
                                        email: userEmailconfig.value,
                                    }
                                },
                            }];
                }
            });
        });
    };
    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, git, res;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, fromBranch = body.fromBranch, toBranch = body.toBranch;
                        return [4 /*yield*/, this.getClient(projectPath)
                            // const res = await git.merge(fromBranch)
                        ];
                    case 1:
                        git = _a.sent();
                        return [4 /*yield*/, git.mergeFromTo(fromBranch, toBranch)
                            // 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 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)
                        ];
                    case 2:
                        tag = _a.sent();
                        // console.log('log', log)
                        return [2 /*return*/, {
                                list: tag.all.map(function (name) {
                                    return {
                                        name: name,
                                    };
                                })
                            }];
                }
            });
        });
    };
    GitService.prototype.tagDelete = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, name, git;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, name = body.name;
                        return [4 /*yield*/, this.getClient(projectPath)];
                    case 1:
                        git = _a.sent();
                        return [4 /*yield*/, this._command(git, ['tag', '--delete', name])];
                    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.tagCreate = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, name, commit, git, params;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        projectPath = body.projectPath, name = body.name, commit = body.commit;
                        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 [2 /*return*/, this._command(git, params)
                            // return {
                            //     commands: [
                            //         {
                            //             command: `git tag ${name}`,
                            //         }
                            //     ],
                            // }
                        ];
                }
            });
        });
    };
    GitService.prototype.commitList = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var projectPath, git, list, 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();
                        list = [];
                        _a.label = 2;
                    case 2:
                        _a.trys.push([2, 4, , 5]);
                        return [4 /*yield*/, git.log()
                            // console.log('log', log)
                        ];
                    case 3:
                        log = _a.sent();
                        // console.log('log', log)
                        list = log.all;
                        return [3 /*break*/, 5];
                    case 4:
                        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*/, 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*/, list];
                }
            });
        });
    };
    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 (!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]];
            });
        });
    };
    return GitService;
}());
exports.GitService = GitService;
//# sourceMappingURL=git.service.js.map