@ts-dev-tools/core
Version:
TS dev tools Core
64 lines (61 loc) • 2.84 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.GitService = void 0;
const node_fs_1 = require("node:fs");
const node_path_1 = require("node:path");
const constants_1 = require("../constants");
const CmdService_1 = require("./CmdService");
class GitService {
constructor() { }
static GIT_HOOK_MODE = 0o755;
static GIT_HOOK_TEMPLATE = `#!/bin/sh
# Created by ${constants_1.PROJECT_NAME} (${constants_1.PROJECT_URL})
%gitHookCommand%`;
static async isGitRepository(absoluteProjectDir) {
return await CmdService_1.CmdService.execCmd("git rev-parse", absoluteProjectDir, true)
.then(() => true)
.catch(() => false);
}
static async addGitHook(absoluteProjectDir, gitHookName, gitHookCommand) {
const gitHookFilePath = GitService.getGitHookFilePath(absoluteProjectDir, gitHookName);
if ((0, node_fs_1.existsSync)(gitHookFilePath)) {
const mode = GitService.getFilePermissions(gitHookFilePath);
if (mode !== GitService.GIT_HOOK_MODE) {
(0, node_fs_1.chmodSync)(gitHookFilePath, GitService.GIT_HOOK_MODE);
}
return;
}
return new Promise((resolve, reject) => {
const stream = (0, node_fs_1.createWriteStream)(gitHookFilePath, {
mode: GitService.GIT_HOOK_MODE,
});
stream.on("close", () => resolve(undefined));
stream.on("error", (error) => reject(error));
stream.write(GitService.GIT_HOOK_TEMPLATE.replace("%gitHookCommand%", gitHookCommand));
stream.end();
});
}
static updateGitHook(absoluteProjectDir, gitHookName, oldGitHookCommand, newGitHookCommand) {
const gitHookFilePath = GitService.getGitHookFilePath(absoluteProjectDir, gitHookName);
if (!(0, node_fs_1.existsSync)(gitHookFilePath)) {
return;
}
const currentHookContent = (0, node_fs_1.readFileSync)(gitHookFilePath, "utf-8");
const oldManagedHookContent = GitService.getManagedGitHookContent(oldGitHookCommand);
if (currentHookContent !== oldManagedHookContent) {
return;
}
(0, node_fs_1.writeFileSync)(gitHookFilePath, GitService.getManagedGitHookContent(newGitHookCommand), { mode: GitService.GIT_HOOK_MODE });
}
static getGitHookFilePath(absoluteProjectDir, gitHookName) {
return (0, node_path_1.join)(absoluteProjectDir, ".git", "hooks", gitHookName);
}
static getManagedGitHookContent(gitHookCommand) {
return GitService.GIT_HOOK_TEMPLATE.replace("%gitHookCommand%", gitHookCommand);
}
static getFilePermissions(filePath) {
const { mode } = (0, node_fs_1.statSync)(filePath);
return mode & 0o777;
}
}
exports.GitService = GitService;