-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathdiffIndexGenerate.ts
More file actions
91 lines (79 loc) · 2.33 KB
/
diffIndexGenerate.ts
File metadata and controls
91 lines (79 loc) · 2.33 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
#!/usr/bin/env node
/**
* AutoCommitMsg CLI script.
*/
import { execFileSync } from "child_process";
import { generateMsg } from "../prepareCommitMsg";
import { shouldShowHelp } from "./utils";
const HELP_TEXT: string = `Usage: acm [--cached] [--help|-h]
Check Git changes and generate a commit message.
Options:
--cached Use only staged changes (equivalent to git --cached).
If the flag is omitted, then the standard \`git status\` logic is followed:
look for staged changes and use them, otherwise use unstaged changes.
--help, -h Show this help and exit.`;
const DIFF_FLAGS = [
"diff-index",
"--name-status",
"--find-renames",
"--find-copies",
"--no-color",
];
/**
* Run `git diff-index` and return its stdout as a string.
*
* TODO: Use _diffIndex instead after refactoring for flags.
* @param useCached When true, include only staged changes using `--cached`.
*
* @returns output Diff output from git.
*/
function runGitDiff(useCached: boolean): string {
const flags: string[] = [...DIFF_FLAGS];
if (useCached) {
flags.push("--cached");
}
flags.push("HEAD");
const output: string = execFileSync("git", flags, {
encoding: "utf8",
stdio: ["ignore", "pipe", "pipe"],
});
return output.trim();
}
/**
* Generate a commit message from the current repository diff.
*
* @param useCached When true, include only staged changes using `--cached`.
* @returns Generated commit message text.
*/
export function generateCommitMessage(useCached: boolean): string {
const diffOutput: string = runGitDiff(useCached);
if (!diffOutput) {
throw new Error("No file changes found");
}
const lines: string[] = diffOutput.split("\n");
return generateMsg(lines);
}
/**
* Command-line entry-point.
*
* Accepts an optional `--cached` flag to use staged changes only.
* Prints the generated commit message to stdout.
*/
function main(argv: string[]): void {
if (shouldShowHelp(argv)) {
console.log(HELP_TEXT);
return;
}
const useCached: boolean = argv.includes("--cached");
const msg: string = generateCommitMessage(useCached);
console.log(msg);
}
if (require.main === module) {
try {
main(process.argv.slice(2));
} catch (err) {
const message: string = err instanceof Error ? err.message : String(err);
console.error(`Error: ${message}`);
process.exit(1);
}
}