forked from conventional-changelog/commitlint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathread.js
75 lines (60 loc) · 1.91 KB
/
read.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
import path from 'path';
import exists from 'path-exists';
import gitRawCommits from '@marionebl/git-raw-commits';
import * as sander from '@marionebl/sander';
import toplevel from './library/toplevel';
export default getCommitMessages;
const SHALLOW_MESSAGE = [
'Could not get git history from shallow clone.',
'Use git fetch --unshallow before linting.',
'Original issue: https://git.io/vyKMq\n Refer to https://git.io/vyKMv for details.'
].join('\n');
// Get commit messages
// Object => Promise<Array<String>>
async function getCommitMessages(settings) {
const {cwd, from, to, edit} = settings;
if (edit) {
return getEditCommit(cwd, edit);
}
if (await isShallow(cwd)) {
throw new Error(SHALLOW_MESSAGE);
}
return getHistoryCommits({from, to}, {cwd});
}
// Get commit messages from history
// Object => Promise<string[]>
function getHistoryCommits(options, opts = {}) {
return new Promise((resolve, reject) => {
const data = [];
gitRawCommits(options, {cwd: opts.cwd})
.on('data', chunk => data.push(chunk.toString('utf-8')))
.on('error', reject)
.on('end', () => {
resolve(data);
});
});
}
// Check if the current repository is shallow
// (cwd: string) => Promise<Boolean>
async function isShallow(cwd) {
const top = await toplevel(cwd);
if (typeof top !== 'string') {
throw new TypeError(`Could not find git root from ${cwd}`);
}
const shallow = path.join(top, '.git/shallow');
return exists(shallow);
}
// Get recently edited commit message
// (cwd: string, edit: any) => Promise<Array<String>>
async function getEditCommit(cwd, edit) {
const top = await toplevel(cwd);
if (typeof top !== 'string') {
throw new TypeError(`Could not find git root from ${cwd}`);
}
const editFilePath =
typeof edit === 'string'
? path.resolve(top, edit)
: path.join(top, '.git/COMMIT_EDITMSG');
const editFile = await sander.readFile(editFilePath);
return [`${editFile.toString('utf-8')}\n`];
}