forked from toplenboren/simple-git-hooks
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple-pre-commit.js
More file actions
210 lines (181 loc) · 6.84 KB
/
simple-pre-commit.js
File metadata and controls
210 lines (181 loc) · 6.84 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
const fs = require('fs')
const os = require("os");
const path = require('path');
/**
* Recursively gets the .git folder path from provided directory
* @param {string} directory
* @return {string | undefined} .git folder path or undefined if it was not found
*/
function getGitProjectRoot(directory=module.parent.filename) {
let start = directory
if (typeof start === 'string') {
if (start[start.length - 1] !== path.sep) {
start += path.sep
}
start = path.normalize(start)
start = start.split(path.sep)
}
if (!start.length) {
return undefined
}
start.pop()
let dir = start.join(path.sep)
let fullPath = path.join(dir, '.git')
if (fs.existsSync(fullPath)) {
if(!fs.lstatSync(fullPath).isDirectory()) {
let content = fs.readFileSync(fullPath, { encoding: 'utf-8' })
let match = /^gitdir: (.*)\s*$/.exec(content)
if (match) {
return path.normalize(match[1])
}
}
return path.normalize(fullPath)
} else {
return getGitProjectRoot(start)
}
}
/**
* Transforms the <project>/node_modules/simple-pre-commit to <project>
* @param projectPath - path to the simple-pre-commit in node modules
* @return {string | undefined} - an absolute path to the project or undefined if projectPath is not in node_modules
*/
function getProjectRootDirectoryFromNodeModules(projectPath) {
function _arraysAreEqual(a1, a2) {
return JSON.stringify(a1) === JSON.stringify(a2)
}
const projDir = projectPath.split(/[\\/]/) // <- would split both on '/' and '\'
if (projDir.length > 2 &&
_arraysAreEqual(projDir.slice(projDir.length - 2, projDir.length), [
'node_modules',
'simple-pre-commit'
])) {
return projDir.slice(0, projDir.length - 2).join('/')
}
return undefined
}
/**
* Checks the 'simple-pre-commit' in dependencies of the project
* @param {string} projectRootPath
* @throws TypeError if packageJsonData not an object
* @return {Boolean}
*/
function checkSimplePreCommitInDependencies(projectRootPath) {
if (typeof projectRootPath !== 'string') {
throw TypeError("Package json path is not a string!")
}
const {packageJsonContent} = _getPackageJson(projectRootPath)
// if simple-pre-commit in dependencies -> note user that he should remove move it to devDeps!
if ('dependencies' in packageJsonContent && 'simple-pre-commit' in packageJsonContent.dependencies) {
console.log('[WARN] You should move simple-pre-commit to the devDependencies!')
return true // We only check that we are in the correct package, e.g not in a dependency of a dependency
}
if (!('devDependencies' in packageJsonContent)) {
return false
}
return 'simple-pre-commit' in packageJsonContent.devDependencies
}
/**
* Gets user-set command either from sources
* First try to get command from .simple-pre-commit.json
* If not found -> try to get command from package.json
* @param {string} projectRootPath
* @throws TypeError if projectRootPath is not string
* @return {string | undefined}
*/
function getCommandFromConfig(projectRootPath) {
if (typeof projectRootPath !== 'string') {
throw TypeError("Check project root path! Expected a string, but got " + typeof projectRootPath)
}
// every function here should accept projectRootPath as first argument and return either string or undefined
const sources = [
() => _getCommandFromFile(projectRootPath, '.simple-pre-commit.json'),
() => _getCommandFromFile(projectRootPath, 'simple-pre-commit.json'),
() => _getCommandFromPackageJson(projectRootPath),
]
for (let i = 0; i < sources.length; ++i) {
let command = sources[i]()
if (command) {
return command
}
}
return undefined
}
/**
* Creates or replaces an existing executable script in .git/hooks/pre-commit with provided command
* @param {string} command
*/
function setPreCommitHook(command) {
const gitRoot = getGitProjectRoot(process.cwd())
const preCommitHook = "#!/bin/sh" + os.EOL + command
const preCommitHookPath = path.normalize(gitRoot + '/hooks/pre-commit')
fs.writeFileSync(preCommitHookPath, preCommitHook)
fs.chmodSync(preCommitHookPath, 0o0755)
}
/**
* Removes the pre-commit hook from .git/hooks
*/
function removePreCommitHook() {
const gitRoot = getGitProjectRoot(process.cwd())
const preCommitHookPath = path.normalize(gitRoot + '/hooks/pre-commit')
fs.unlinkSync(preCommitHookPath)
}
/** Reads package.json file, returns package.json content and path
* @param {string} projectPath - a path to the project, defaults to process.cwd
* @return {{packageJsonContent: any, packageJsonPath: string}}
* @throws TypeError if projectPath is not a string
* @throws Error if cant read package.json
* @private
*/
function _getPackageJson(projectPath = process.cwd()) {
if (typeof projectPath !== "string") {
throw TypeError("projectPath is not a string")
}
const targetPackageJson = path.normalize(projectPath + '/package.json')
if (!fs.statSync(targetPackageJson).isFile()) {
throw Error("Package.json doesn't exist")
}
const packageJsonDataRaw = fs.readFileSync(targetPackageJson)
return { packageJsonContent: JSON.parse(packageJsonDataRaw), packageJsonPath: targetPackageJson }
}
/**
* Gets current command from package.json[simple-pre-commit]
* @param {string} projectRootPath
* @throws TypeError if packageJsonPath is not a string
* @throws Error if package.json couldn't be read
* @return {undefined | string}
*/
function _getCommandFromPackageJson(projectRootPath = process.cwd()) {
const {packageJsonContent} = _getPackageJson(projectRootPath)
return packageJsonContent['simple-pre-commit']
}
/**
* Gets user-set command from file
* Since the file is not required in node.js projects it returns undefined if something is off
* @param {string} projectRootPath
* @param {string} fileName
* @return {string | undefined}
*/
function _getCommandFromFile(projectRootPath, fileName) {
if (typeof projectRootPath !== "string") {
throw TypeError("projectRootPath is not a string")
}
if (typeof fileName !== "string") {
throw TypeError("fileName is not a string")
}
try {
const simplePreCommitJsonPath = path.normalize(projectRootPath + '/' + fileName)
const simplePreCommitJsonRaw = fs.readFileSync(simplePreCommitJsonPath)
const simplePreCommitJson = JSON.parse(simplePreCommitJsonRaw)
return simplePreCommitJson['simple-pre-commit']
} catch (err) {
return undefined
}
}
module.exports = {
checkSimplePreCommitInDependencies,
setPreCommitHook,
getCommandFromConfig,
getProjectRootDirectoryFromNodeModules,
getGitProjectRoot,
removePreCommitHook
}