-
Notifications
You must be signed in to change notification settings - Fork 4
/
install-git-hooks.js
60 lines (52 loc) · 1.72 KB
/
install-git-hooks.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
const fs = require("fs");
const path = require("path");
function installGitHooks(args) {
const libPath = path.dirname(require.main.filename);
const regexPath = /^(.*?)node_modules/.exec(libPath);
const appRoot = regexPath ? regexPath[1] : libPath;
const package = require(`${appRoot}package.json`);
let repoPath = "./";
let gitHooksPath = "./.githooks";
if (package["node-git-hooks"]) {
if (package["node-git-hooks"]["repo-path"]) {
repoPath = package["node-git-hooks"]["repo-path"];
}
if (package["node-git-hooks"]["githooks-path"]) {
gitHooksPath = package["node-git-hooks"]["githooks-path"];
}
}
if (!fs.existsSync(`${repoPath}.git`) || !fs.existsSync(`${repoPath}.git/hooks`)) {
console.log("The installation isn't a Git repo. Skipping hooks installation.");
return 0;
}
if (!fs.existsSync(gitHooksPath)) {
console.log("No .githooks folder found. Skipping hooks installation.");
return 0;
}
console.log("Installing Git hooks...");
try {
copyDir(gitHooksPath, `${repoPath}.git/hooks`);
} catch (error) {
console.error("Error copying Git hooks: ", error);
return 1;
}
return 0;
}
function copyDir(src, dest) {
const files = fs.readdirSync(src);
for (let file of files) {
const current = fs.lstatSync(path.join(src, file));
if (current.isDirectory()) {
copyDir(path.join(src, file), path.join(dest, file));
} else if (current.isSymbolicLink()) {
const symlink = fs.readlinkSync(path.join(src, file));
fs.symlinkSync(symlink, path.join(dest, file));
} else {
copy(path.join(src, file), path.join(dest, file));
}
}
};
function copy(src, dest) {
fs.copyFileSync(src, dest);
};
module.exports = installGitHooks;