-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgit-api.js
86 lines (68 loc) · 2.23 KB
/
git-api.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
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
const { spawn } = require('child_process')
const readline = require('readline')
const ComplexityCalculator = require('./complexity-calculator')
class GitApi {
constructor (tabLength) {
this._complexityCalculator = new ComplexityCalculator(tabLength)
}
catFile (blobHash) {
const command = spawn('git', ['cat-file', 'blob', blobHash])
command.stdout.setEncoding('utf8')
command.stderr.setEncoding('utf8')
return command
}
log (file) {
return this._runCommand(['--no-pager', 'log', '--pretty=format:%H %aI', '--follow', '--', file], this._parseGitLog, [file])
}
lsFiles () {
return this._runCommand(['ls-files'], this._parseGitLsFiles)
}
lsTree (gitHash, fileName) {
return this._runCommand(['ls-tree', gitHash, '--', fileName], this._parseGitLsTree)
}
whitespaceComplexity (blobHash) {
return this._runCommand(['cat-file', 'blob', blobHash], this._getWhitespaceComplexity.bind(this))
}
_runCommand (args, action, actionArgs = []) {
return new Promise((resolve, reject) => {
let result
const command = spawn('git', args)
command.stdout.setEncoding('utf8')
command.stderr.setEncoding('utf8')
command.stderr.on('data', (data) => reject(data))
const rl = readline.createInterface({ input: command.stdout })
rl.on('close', () => {
resolve(result)
})
if(action) {
rl.on('line', (line) => {
result = action(line, result, ...actionArgs)
})
}
})
}
_getWhitespaceComplexity (line, complexity) {
if (!complexity) { complexity = 0 }
complexity += this._complexityCalculator.whiteSpaceComplexity(line)
return complexity
}
_parseGitLog (line, results, fileName) {
const lineParts = line.split(' ')
const gitHash = lineParts[0]
const authorDate = /\d{4}-\d{2}-\d{2}/.exec(lineParts[1])[0]
if (!results) { results = [] }
results.push({ fileName, authorDate, gitHash })
return results
}
_parseGitLsTree (line) {
const regexFilter = /(blob\s.+)(\s)/
const match = regexFilter.exec(line)
return match[1].split(' ')[1]
}
_parseGitLsFiles (file, results) {
if (!results) { results = [] }
results.push(file)
return results
}
}
module.exports = GitApi