-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
319 lines (275 loc) · 9.3 KB
/
index.js
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
const core = require("@actions/core");
const exec = require("@actions/exec");
const tc = require("@actions/tool-cache");
const os = require("os");
const path = require("path");
const fs = require("fs");
const https = require("https");
// Function to parse Unix-style activation script
async function parseUnixScript(scriptPath) {
const content = await fs.promises.readFile(scriptPath, "utf8");
const commands = {};
// Parse alias definitions
const aliasRegex = /alias\s+([^=]+)="([^"]+)"/g;
let match;
while ((match = aliasRegex.exec(content)) !== null) {
const [_, cmd, fullPath] = match;
commands[cmd] = fullPath;
}
return commands;
}
// Function to parse Windows PowerShell script
async function parseWindowsScript(scriptPath) {
const content = await fs.promises.readFile(scriptPath, "utf8");
const commands = {};
// Parse function definitions
const functionRegex = /function global:([^\s{]+)\s*{[\r\n\s]*([^}]+)}/g;
let match;
while ((match = functionRegex.exec(content)) !== null) {
const [_, functionName, functionBody] = match;
// Clean up the command by taking the first non-empty line
const command = functionBody
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0)[0];
commands[functionName] = command.replace(" @args", "");
}
// Special handling for Invoke-idfpy which becomes idf.py
if (commands["Invoke-idfpy"]) {
commands["idf.py"] = commands["Invoke-idfpy"];
delete commands["Invoke-idfpy"];
}
return commands;
}
async function run() {
try {
// Get inputs
const version = core.getInput("version");
let idfPath = core.getInput("path");
let toolsPath = core.getInput("tools-path");
// Set default paths if not provided
if (!idfPath) {
idfPath = process.platform === "win32" ? "C:\\esp\\idf" : "/tmp/esp/idf";
}
if (!toolsPath) {
toolsPath = process.platform === "win32" ? "C:\\esp" : "/tmp/esp";
}
// Install platform-specific dependencies
await installDependencies(process.platform);
// Get latest EIM version from GitHub
const eimVersion = await getLatestEimVersion();
core.info(`Using EIM version: ${eimVersion}`);
// Get the appropriate EIM download URL
const downloadUrl = getEimDownloadUrl(
process.platform,
process.arch,
eimVersion
);
// Download and extract EIM
core.info(`Downloading EIM from ${downloadUrl}`);
const downloadedPath = await tc.downloadTool(downloadUrl);
const extractedPath = await tc.extractZip(downloadedPath);
// Make EIM executable on Unix systems
if (process.platform !== "win32") {
await exec.exec("chmod", ["+x", path.join(extractedPath, "eim")]);
}
// Prepare EIM command and execute installation
const eimCmd = process.platform === "win32" ? "eim.exe" : "./eim";
const eimPath = path.join(extractedPath, eimCmd);
const args = ["-r", "true", "-n", "true", "-a", "true"];
if (version !== "latest" && version.trim().length > 0) {
core.info(`Installing ESP-IDF version |${version}|`);
args.push("-i", version);
}
args.push("-p", idfPath);
args.push("--tool-install-folder-name", toolsPath);
// Run EIM
core.info("Running EIM installation...");
await exec.exec(eimPath, args);
// Find and execute the appropriate activation script
core.info("Finding environment setup script...");
let output = "";
const options = {
listeners: {
stdout: (data) => {
output += data.toString();
},
},
};
// Find and parse activation script
let scriptPath;
let commands;
if (process.platform === "win32") {
const files = await fs.promises.readdir(idfPath);
const versionDir = files.find((f) => /^v\d+\.\d+$/.test(f));
if (!versionDir) {
throw new Error("Could not find version directory in IDF path");
}
scriptPath = path.join(
idfPath,
versionDir,
"Microsoft.PowerShell_profile.ps1"
);
if (
!(await fs.promises
.access(scriptPath)
.then(() => true)
.catch(() => false))
) {
throw new Error("Could not find PowerShell profile script");
}
// Parse Windows commands
commands = await parseWindowsScript(scriptPath);
// Execute PowerShell profile
await exec.exec(
"powershell",
["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", scriptPath, "-e"],
options
);
} else {
const files = await fs.promises.readdir(idfPath);
const activationFile = files.find(
(f) => f.startsWith("activate_") && f.endsWith(".sh")
);
if (!activationFile) {
throw new Error("Could not find activation script");
}
scriptPath = path.join(idfPath, activationFile);
await exec.exec("chmod", ["+x", scriptPath]);
// Parse Unix commands
commands = await parseUnixScript(scriptPath);
// Execute activation script
await exec.exec(scriptPath, ["-e"], options);
}
// Parse the output and set environment variables
const envVars = {};
output.split("\n").forEach((line) => {
const match = line.match(/^([^=]+)=(.*)$/);
if (match) {
const [, key, value] = match;
envVars[key] = value;
}
});
// Set environment variables
for (const [key, value] of Object.entries(envVars)) {
if (key === "PATH") {
const newPaths = value.split(path.delimiter).filter(Boolean);
for (const newPath of newPaths) {
core.addPath(newPath);
}
} else {
core.exportVariable(key, value);
}
core.info(`Set ${key}`);
}
// Create bin directory for wrapper scripts
const binDir = path.join(toolsPath, "bin");
await fs.promises.mkdir(binDir, { recursive: true });
// Create wrapper scripts based on parsed commands
for (const [cmd, fullPath] of Object.entries(commands)) {
const wrapperPath = path.join(binDir, cmd);
if (process.platform === "win32") {
// Create .cmd file for Windows
const cmdContent = `@echo off\r\n${fullPath} %*`;
await fs.promises.writeFile(wrapperPath + ".cmd", cmdContent);
} else {
// Create shell script for Unix
const shContent = `#!/bin/bash\n${fullPath} "$@"`;
await fs.promises.writeFile(wrapperPath, shContent);
await exec.exec("chmod", ["+x", wrapperPath]);
}
}
// Add bin directory to PATH
core.addPath(binDir);
core.info(
"ESP-IDF installation and environment setup completed successfully"
);
} catch (error) {
core.setFailed(error.message || "An unexpected error occurred");
}
}
// Function to fetch latest release version from GitHub API
async function getLatestEimVersion() {
return new Promise((resolve, reject) => {
const options = {
hostname: "dl.espressif.com",
path: "/dl/eim/eim_cli_release.json",
headers: {
"User-Agent": "GitHub-Action-ESP-IDF-Setup",
},
};
const req = https.get(options, (res) => {
let data = "";
res.on("data", (chunk) => {
data += chunk;
});
res.on("end", () => {
if (res.statusCode === 200) {
try {
const release = JSON.parse(data);
resolve(release.tag_name);
} catch (error) {
reject(new Error("Failed to parse eim_cli_release,.json"));
}
} else {
reject(
new Error(
`dl.espressif.com request failed with status ${res.statusCode}`
)
);
}
});
});
req.on("error", (error) => {
reject(error);
});
req.end();
});
}
function getEimDownloadUrl(platform, arch, version) {
const baseUrl = "https://github.com/espressif/idf-im-cli/releases/download";
switch (platform) {
case "linux":
return `${baseUrl}/${version}/eim-${version}-linux-${
arch === "arm64" ? "arm64" : "x64"
}.zip`;
case "darwin":
return `${baseUrl}/${version}/eim-${version}-macos-${
arch === "arm64" ? "aarch64" : "x64"
}.zip`;
case "win32":
return `${baseUrl}/${version}/eim-${version}-windows-x64.zip`;
default:
throw new Error(`Unsupported platform: ${platform}`);
}
}
async function installDependencies(platform) {
switch (platform) {
case "linux":
try {
await exec.exec("which apt-get");
} catch (error) {
core.setFailed(
"--------------- WARNING ---------------\n" +
"This action currently supports only official GitHub-hosted Ubuntu runners. " +
"If you're using a self-hosted runner or a different Linux distribution, " +
"please ensure all required dependencies are pre-installed."
);
return;
}
await exec.exec("sudo apt-get update");
await exec.exec(
"sudo apt-get install -y git cmake ninja-build wget flex bison gperf ccache libffi-dev libssl-dev dfu-util libusb-1.0-0 python3 python3-pip python3-setuptools python3-wheel xz-utils unzip python3-venv"
);
break;
case "darwin":
await exec.exec("brew install dfu-util cmake ninja");
break;
case "win32":
// No dependencies needed for Windows
break;
default:
throw new Error(`Unsupported platform: ${platform}`);
}
}
run();