-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
138 lines (119 loc) · 4.1 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
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
import * as core from "@actions/core";
import { exec, ExecOptions } from "@actions/exec";
import glob from "glob";
/**
* Find files using a glob pattern.
* @param filePattern The glob pattern to search for files.
* @returns A promise that resolves with an array of file paths matching the pattern.
*/
const findFilesWithGlob = (filePattern: string): Promise<string[]> => {
return new Promise<string[]>((resolve, reject) => {
glob(filePattern, (error: Error | null, files: string[]) => {
if (error) {
reject(error);
} else {
resolve(files);
}
});
});
};
/**
* Execute a command asynchronously.
* @param command The command to execute.
* @param options Optional configuration options for the execution.
* @returns A promise that resolves with the execution result.
*/
const execute = async (
command: string,
{ silent = false }: { silent?: boolean } = {}
): Promise<{ err: boolean; stdOut: string; stdErr: string }> => {
let stdOut: string = "";
let stdErr: string = "";
const options: ExecOptions = {
silent,
ignoreReturnCode: true,
listeners: {
stdout: (data: Buffer) => (stdOut += data.toString()),
stderr: (data: Buffer) => (stdErr += data.toString()),
},
};
const exitCode: number = await exec(command, undefined, options);
return { err: exitCode !== 0, stdErr, stdOut };
};
/**
* Execute a `git push`.
*/
const push = async (): Promise<void> => {await execute("git push")};
/**
* Main function that formats RST files based on the provided configuration.
*/
const main = async (): Promise<void> => {
const DEBUG: boolean = core.isDebug();
const args: string = core.getInput("rstfmt-args") || "";
const filePatterns: string[] = core.getMultilineInput("files") || ["**/*.rst"];
const commitString: string = core.getInput("commit") || "true";
const commit: boolean = commitString.toLowerCase() !== "false";
const githubUsername: string = core.getInput("github-username") || "github-actions";
const commitMessage: string = core.getInput("commit-message") || "Format RST files";
await core.group("Installing rstfmt", async (): Promise<void> => {
await execute("pip install rstfmt", { silent: true });
});
let rstFiles: string[] = [];
for (const filePattern of filePatterns) {
const files: string[] = await findFilesWithGlob(filePattern);
rstFiles = rstFiles.concat(files);
}
if (rstFiles.length === 0) {
core.info("No RST files found.");
return;
}
const individualFiles: string[] = rstFiles.join("\n").split("\n");
const formatCommands: string[] = individualFiles.map((file) => `rstfmt ${file}`);
core.debug(`Current working directory: ${process.cwd()}`);
core.debug(`Formatting RST files: ${individualFiles.join(", ")}`);
core.debug(`Format command: ${formatCommands.join(", ")}`);
const formatResult: { err: boolean; stdOut: string; stdErr: string }[] = await Promise.all(
formatCommands.map((command) => execute(command))
);
const failedFiles: string[] = formatResult
.filter((result) => result.err)
.map((result, index) => {
const cmdIndex: number = formatResult.findIndex((r) => r === result);
const failedFile: string = individualFiles[cmdIndex];
core.error(`Error formatting RST file: ${failedFile}`);
core.error(`Error message: ${result.stdErr}`);
return failedFile;
});
if (failedFiles.length > 0) {
core.error(`Error formatting RST files: ${failedFiles.join(", ")}`);
core.setFailed("Error formatting RST files.");
return;
}
core.info("RST files formatted successfully.");
if (commit) {
await core.group("Committing changes", async (): Promise<void> => {
await execute(`git config user.name "${githubUsername}"`, {
silent: true,
});
await execute('git config user.email ""', { silent: true });
const { err: diffErr }: { err: boolean } = await execute("git diff-index --quiet HEAD", {
silent: true,
});
if (!diffErr) {
core.info("Nothing to commit!");
} else {
await execute(`git commit --all -m "${commitMessage}"`);
await push();
}
});
}
};
try {
main();
} catch (err: unknown) {
if (err instanceof Error) {
core.setFailed(err.message);
} else {
core.setFailed("An error occurred.");
}
}