Repository navigation
Expand file tree
/
Copy pathaction.js
More file actions
205 lines (177 loc) · 6.37 KB
/
Copy pathaction.js
File metadata and controls
205 lines (177 loc) · 6.37 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
import { exec } from "node:child_process";
import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
import os from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";
import { promisify } from "node:util";
import { getInput, info, setOutput, warning } from "@actions/core";
const execAsync = promisify(exec);
const CORE_PACKAGE_NAME = "@stats-organization/github-readme-stats-core";
const validateCoreVersion = (value) => {
const pattern = /^[a-zA-Z0-9._-]*$/;
if (!pattern.test(value)) {
throw new Error("core_version must contain only a-zA-Z0-9._- characters.");
}
return value;
};
/**
* Install the requested core package into an isolated temporary directory.
* @param {string} version Package version.
* @returns {Promise<string>} Directory containing the installed package.
*/
const installCorePackage = async (version) => {
const installDir = await mkdtemp(path.join(os.tmpdir(), "grs-core-"));
const npmCommand = process.platform === "win32" ? "npm.cmd" : "npm";
const packageSpec = `${CORE_PACKAGE_NAME}@${version}`;
try {
await writeFile(
path.join(installDir, "package.json"),
JSON.stringify({ private: true, type: "module" }),
"utf8",
);
await execAsync(
`${npmCommand} install --no-save --ignore-scripts --no-package-lock ${packageSpec}`,
{
cwd: installDir,
env: process.env,
},
);
return installDir;
} catch (error) {
throw new Error(`Failed to install ${packageSpec}: ${error}`);
}
};
/**
* Load the core package either from the bundled dependency or from an isolated install.
* @param {string} version Package version.
* @returns {Promise<Record<string, unknown>>} Loaded module and cleanup callback.
*/
const loadCoreModule = async (version) => {
if (!version) {
return await import(CORE_PACKAGE_NAME);
}
const installDir = await installCorePackage(version);
const installRequire = createRequire(path.join(installDir, "package.json"));
const modulePath = installRequire.resolve(CORE_PACKAGE_NAME);
return await import(pathToFileURL(modulePath).href);
};
/**
* Map of supported card types to the core export to call and the option each requires.
* @type {Record<string, { exportName: string, requires: string }>}
*/
const CARDS = {
stats: { exportName: "api", requires: "username" },
"top-langs": { exportName: "topLangs", requires: "username" },
pin: { exportName: "pin", requires: "repo" },
wakatime: { exportName: "wakatime", requires: "username" },
gist: { exportName: "gist", requires: "id" },
};
/**
* Parse options from query string or JSON and normalize values to strings.
* @param {string} value Input value.
* @returns {Record<string, string>} Parsed options.
*/
export const parseOptions = (value) => {
const trimmed = value?.trim();
if (!trimmed) {
return {};
}
if (trimmed.startsWith("{")) {
let parsed;
try {
parsed = JSON.parse(trimmed);
} catch {
throw new Error("Invalid JSON in options.");
}
return Object.fromEntries(
Object.entries(parsed)
.filter(([, val]) => val !== null && val !== undefined)
.map(([key, val]) => [
key,
Array.isArray(val) ? val.join(",") : String(val),
]),
);
}
const params = new URLSearchParams(trimmed);
return Object.fromEntries(
[...new Set(params.keys())].map((key) => [
key,
params.getAll(key).join(","),
]),
);
};
/**
* Generate the requested card and write it to disk.
*/
export const run = async () => {
const card = getInput("card", { required: true }).toLowerCase();
const optionsInput = getInput("options");
const outputPathInput = getInput("path");
const coreVersion = validateCoreVersion(getInput("core_version"));
const failOnError = /^(true|1|yes)$/i.test(getInput("fail_on_error"));
const cardDef = CARDS[card];
if (!cardDef) {
throw new Error(`Unsupported card type: ${card}`);
}
const coreModule = await loadCoreModule(coreVersion);
for (const { exportName } of Object.values(CARDS)) {
if (typeof coreModule[exportName] !== "function") {
throw new Error(
`Loaded ${CORE_PACKAGE_NAME} does not expose the expected '${exportName}' function.`,
);
}
}
const query = parseOptions(optionsInput);
if (!query.username && process.env.GITHUB_REPOSITORY_OWNER) {
// keep previous behavior for backwards compatibility;
// repo cards may use `username` even though it's not required
query.username = process.env.GITHUB_REPOSITORY_OWNER;
if (cardDef.requires === "username") {
info("username not provided; defaulting to repository owner.");
}
}
if (!query[cardDef.requires]) {
throw new Error(`${cardDef.requires} is required for the ${card} card.`);
}
const handler = coreModule[cardDef.exportName];
const outputPathValue =
outputPathInput || path.join("profile", `${card}.svg`);
const outputPath = path.resolve(process.cwd(), outputPathValue);
const result = await handler(query);
const svg = result?.content;
// The core renderer never throws on a data-fetch error; it returns a `status`
// starting with "error" and a "Something went wrong" SVG. When fail_on_error
// is enabled, fail the action so the broken card is never written or committed.
// Older core versions may not return a `status`, so this is a no-op for them.
if (String(result?.status).startsWith("error")) {
setOutput("error_type", result.error?.type ?? "");
setOutput("error_message", result.error?.message ?? "");
setOutput("error_secondary_message", result.error?.secondaryMessage ?? "");
let message;
if (result.error?.message && result.error?.secondaryMessage) {
message = `${result.error.message} - ${result.error.secondaryMessage}`;
} else {
message =
result.error?.message ??
result.error?.secondaryMessage ??
result.status;
}
if (result.error?.type) {
message += ` [${result.error.type}]`;
}
message = "Card generation failed: " + message;
if (failOnError) {
throw new Error(message);
} else {
warning(message);
}
}
if (!svg) {
throw new Error("Card renderer returned empty output.");
}
await mkdir(path.dirname(outputPath), { recursive: true });
await writeFile(outputPath, svg, "utf8");
info(`Wrote ${outputPath}`);
setOutput("path", outputPathValue);
};