-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.ts
More file actions
326 lines (287 loc) · 9.62 KB
/
main.ts
File metadata and controls
326 lines (287 loc) · 9.62 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
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
import { exec, getExecOutput } from "@actions/exec";
import * as core from "@actions/core";
import * as fs from "node:fs/promises";
import { logInfoAndDebug, toJson, toJsonPretty } from "./logging";
import { multiplePrBody, singlePrBody } from "./markdown";
import { z } from "zod";
import { getCommit, getPreviousTag, getTag, hasTag } from "./git";
import { parse } from "ini";
const updateStrategy = z.enum(["commit", "tag"]);
type UpdateStrategy = z.infer<typeof updateStrategy>;
const submodule = z.object({
path: z.string(),
url: z.string().regex(/[A-Za-z][A-Za-z0-9+.-]*/),
});
const gitmodulesSchema = z.record(
z.string(),
z.union([
submodule,
z.record(z.string(), submodule)
])
).transform(submodules => {
return Object.entries(submodules)
.map(([key, value]) => {
if (value.path && value.url) return { [key]: value };
const [[nestedKey, nestedValue]] = Object.entries(value);
return { [`${key} .${nestedKey}`]: nestedValue };
})
.reduce((prev, curr) => ({ ...prev, ...curr }), {});
});
export type Inputs = {
gitmodulesPath: string;
inputSubmodules: string[];
strategy: UpdateStrategy;
};
export type Submodule = {
name: string;
path: string;
url: string;
remoteName: string;
previousShortCommitSha: string;
previousCommitSha: string;
previousCommitShaHasTag: boolean;
previousTag?: string;
latestShortCommitSha: string;
latestCommitSha: string;
latestTag?: string;
};
export type UpdatedSubmodule = {
path: string;
shortCommitSha: string;
commitSha: string;
};
type GAMatrix = {
name: string[];
include: Submodule[];
};
export const parseInputs = async (): Promise<Inputs> => {
const gitmodulesPath = core.getInput("gitmodulesPath").trim();
const inputSubmodules = core.getInput("submodules").trim();
const strategy = await updateStrategy.parseAsync(
core.getInput("strategy").trim()
);
// Github Actions doesn't support array inputs, so submodules must be separated by newlines
const parsedSubmodules = inputSubmodules
.split("\n")
.map((submodule) => submodule.trim().replace(/"/g, ""));
core.debug(`Input submodules: ${toJsonPretty(parsedSubmodules)}`);
return {
gitmodulesPath,
inputSubmodules: inputSubmodules === "" ? [] : parsedSubmodules,
strategy,
};
};
export const readFile = async (path: string): Promise<string> => {
return await fs.readFile(path, "utf8").catch((error) => {
if (error instanceof Error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
core.setFailed(`File not found: ${path}`);
} else {
core.setFailed(`Error reading file: ${error.message}`);
}
} else {
core.setFailed("An unknown error occurred while reading the file");
}
throw error;
});
};
export const getRemoteName = (url: string) => {
url = url.replace(/\.git\/?/, "")
let startIndex = url.length - 1;
// Scan backwards to find separator.
while (startIndex >= 0) {
if (url[startIndex] == "~" || url[startIndex] == ":") {
startIndex++;
break;
} else if (url[startIndex] == ".") {
break;
}
startIndex--;
}
// If we broke on a dot, we _probably_ hit a domain label, so
// scan forward until we hit a slash.
if (url[startIndex] == ".") {
while (url[startIndex] != "/") {
startIndex++;
}
}
return url.substring(startIndex).replace(/^\/+/, "");
}
export const parseGitmodules = async (
content: string
): Promise<Submodule[]> => {
const parsed = parse(content);
const gitmodules = await gitmodulesSchema.parseAsync(parsed);
return await Promise.all(
Object.entries(gitmodules).map(async ([key, values]) => {
const name = key.split('"')[1].trim();
const path = values.path.replace(/"/g, "").trim();
const url = values.url.replace(/"/g, "").trim();
const remoteName = getRemoteName(url);
const [previousCommitSha, previousShortCommitSha] = await getCommit(path);
const previousCommitShaHasTag = await hasTag(path, previousCommitSha);
const previousTag = await getPreviousTag(path);
return {
name,
path,
url,
remoteName,
previousShortCommitSha,
previousCommitSha,
previousCommitShaHasTag,
previousTag,
// The latest commit should be updated after the submodule is updated
// If you think about it, the "previous" commit is the latest commit too
latestShortCommitSha: previousShortCommitSha,
latestCommitSha: previousCommitSha,
};
})
);
};
export const filterSubmodules = async (
inputSubmodules: string[],
detectedSubmodules: Submodule[],
strategy: UpdateStrategy
): Promise<Submodule[]> => {
let validSubmodules = detectedSubmodules;
if (strategy === "tag") {
validSubmodules = detectedSubmodules.filter(
(submodule) => submodule.previousTag
);
}
if (inputSubmodules.length === 0) {
return validSubmodules;
}
return validSubmodules.filter((submodule) =>
inputSubmodules.some((input) => input === submodule.path)
);
};
export const updateToLatestCommit = async (
filteredSubmodules: Submodule[]
): Promise<Submodule[]> => {
const paths = filteredSubmodules.map((submodule) => submodule.path);
const { stdout } = await getExecOutput(
"git submodule update --remote",
paths
);
if (stdout.trim() === "") {
return [];
}
// Parse the updated submodules from the git output
// ASSUMPTION: The first set of single quotes is the submodule path
// ASSUMPTION: The second set of single quotes is the commit sha
const updatedSubmodules: UpdatedSubmodule[] = stdout
.trim()
.split("\n")
.map((line) => {
const path = line.split("'")[1];
const commitSha = line.split("'")[3];
return {
path,
commitSha,
shortCommitSha: commitSha.substring(0, 7),
};
});
core.debug(
`Submodules parsed from git output: ${toJsonPretty(updatedSubmodules)}`
);
for (const { path, shortCommitSha, commitSha } of updatedSubmodules) {
const submodule = filteredSubmodules.find(
(submodule) => submodule.path === path
);
if (submodule) {
submodule.latestShortCommitSha = shortCommitSha;
submodule.latestCommitSha = commitSha;
}
}
// We only want to update the submodules that actually have new commits
return filteredSubmodules.filter((submodule) => {
return updatedSubmodules.some((updated) => updated.path === submodule.path);
});
};
export const updateToLatestTag = async (
updatedSubmodules: Submodule[]
): Promise<Submodule[]> => {
const submodulesWithTag = updatedSubmodules.map(async (submodule) => {
const options = { cwd: submodule.path };
const latestTag = await getTag(submodule.path);
await exec(`git reset --hard`, [latestTag], options);
return { ...submodule, latestTag } as Submodule;
});
return await Promise.all(submodulesWithTag);
};
export const setDynamicOutputs = (prefix: string, submodule: Submodule) => {
core.setOutput(`${prefix}--updated`, true);
core.setOutput(`${prefix}--path`, submodule.path);
core.setOutput(`${prefix}--url`, submodule.url);
core.setOutput(`${prefix}--url`, submodule.remoteName);
core.setOutput(
`${prefix}--previousShortCommitSha`,
submodule.previousShortCommitSha
);
core.setOutput(`${prefix}--previousCommitSha`, submodule.previousCommitSha);
core.setOutput(
`${prefix}--latestShortCommitSha`,
submodule.latestShortCommitSha
);
core.setOutput(`${prefix}--latestCommitSha`, submodule.latestCommitSha);
core.setOutput(`${prefix}--previousTag`, submodule.previousTag ?? "");
core.setOutput(`${prefix}--latestTag`, submodule.latestTag ?? "");
core.setOutput(`${prefix}--prBody`, singlePrBody(submodule));
};
const toJsonMatrix = (submodules: Submodule[]): string => {
const matrix: GAMatrix = {
name: submodules.map((submodule) => submodule.name),
include: submodules,
};
return toJson(matrix);
};
/**
* The main function for the action.
*/
export async function run(): Promise<void> {
try {
const { gitmodulesPath, inputSubmodules, strategy } = await parseInputs();
const gitmodulesContent = await readFile(gitmodulesPath);
if (gitmodulesContent === "") {
core.info("No submodules detected.");
core.info("Nothing to do. Exiting...");
return;
}
const detectedSubmodules = await parseGitmodules(gitmodulesContent);
logInfoAndDebug("Detected Submodules", detectedSubmodules);
const validSubmodules = await filterSubmodules(
inputSubmodules,
detectedSubmodules,
strategy
);
if (validSubmodules.length === 0) {
core.info("No valid submodules detected.");
core.info("Nothing to do. Exiting...");
return;
}
logInfoAndDebug("Valid submodules", validSubmodules);
const updatedSubmodules = await updateToLatestCommit(validSubmodules);
if (updatedSubmodules.length === 0) {
core.info("All submodules have no new remote commits.");
core.info("Nothing to do. Exiting...");
return;
}
logInfoAndDebug("Updated submodules", updatedSubmodules);
let outputSubmodules = updatedSubmodules;
if (strategy === "tag") {
outputSubmodules = await updateToLatestTag(updatedSubmodules);
}
core.setOutput("json", toJson(outputSubmodules));
core.setOutput("matrix", toJsonMatrix(outputSubmodules));
core.setOutput("prBody", multiplePrBody(outputSubmodules));
for (const submodule of outputSubmodules) {
setDynamicOutputs(submodule.name, submodule);
if (submodule.name !== submodule.path) {
setDynamicOutputs(submodule.path, submodule);
}
}
} catch (error) {
if (error instanceof Error) core.setFailed(error.message);
}
}