forked from conventional-changelog/commitlint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
87 lines (73 loc) · 2.17 KB
/
index.ts
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
import path from 'path';
import {Stats} from 'fs';
import Buffer from 'buffer';
import {Readable} from 'stream';
import toplevel from '@commitlint/top-level';
const gitRawCommits = require('git-raw-commits');
const sander = require('@marionebl/sander');
interface Settings {
cwd?: string;
from?: string;
to?: string;
edit?: boolean | string;
}
export default getCommitMessages;
// Get commit messages
async function getCommitMessages(settings: Settings): Promise<string[]> {
const {cwd, from, to, edit} = settings;
if (edit) {
return getEditCommit(cwd, edit);
}
return getHistoryCommits({from, to}, {cwd});
}
// Get commit messages from history
function getHistoryCommits(
options: {from?: string; to?: string},
opts: {cwd?: string} = {}
): Promise<string[]> {
return new Promise((resolve, reject) => {
const data: string[] = [];
(gitRawCommits(options, {cwd: opts.cwd}) as Readable)
.on('data', chunk => data.push(chunk.toString('utf-8')))
.on('error', reject)
.on('end', () => {
resolve(data);
});
});
}
// Get recently edited commit message
async function getEditCommit(
cwd?: string,
edit?: boolean | string
): Promise<string[]> {
const top = await toplevel(cwd);
if (typeof top !== 'string') {
throw new TypeError(`Could not find git root from ${cwd}`);
}
const editFilePath = await getEditFilePath(top, edit);
const editFile: Buffer = await sander.readFile(editFilePath);
return [`${editFile.toString('utf-8')}\n`];
}
// Get path to recently edited commit message file
async function getEditFilePath(
top: string,
edit?: boolean | string
): Promise<string> {
let editFilePath: string;
if (typeof edit === 'string') {
editFilePath = path.resolve(top, edit);
} else {
const dotgitPath = path.join(top, '.git');
const dotgitStats: Stats = sander.lstatSync(dotgitPath);
if (dotgitStats.isDirectory()) {
editFilePath = path.join(top, '.git/COMMIT_EDITMSG');
} else {
const gitFile: string = await sander.readFile(dotgitPath, {
encoding: 'utf-8'
});
const relativeGitPath = gitFile.replace('gitdir: ', '').replace('\n', '');
editFilePath = path.resolve(top, relativeGitPath, 'COMMIT_EDITMSG');
}
}
return editFilePath;
}