|
| 1 | +// apio-downloader.js |
| 2 | +// Ensures that the apio pyinstaller bundle is installed and that |
| 3 | +// the apio binary is available at ~/.apio/bin/apio[.exe]. If not, |
| 4 | +// It's downloaded and installed on the fly. |
| 5 | + |
| 6 | +"use strict"; |
| 7 | + |
| 8 | +// Standard imports |
| 9 | +const fs = require("fs"); |
| 10 | +const path = require("path"); |
| 11 | +const os = require("os"); |
| 12 | +const stream = require("node:stream"); |
| 13 | +const childProcess = require("child_process"); |
| 14 | +const assert = require("node:assert"); |
| 15 | + |
| 16 | +// Dependency imports |
| 17 | +const zipExtract = require("extract-zip"); |
| 18 | +const tar = require("tar"); |
| 19 | + |
| 20 | +// Local imports |
| 21 | +const platforms = require("./apio-platforms.js"); |
| 22 | +const apioLog = require("./apio-log.js"); |
| 23 | + |
| 24 | +// The release to download |
| 25 | + const apioReleaseTag = "2025-11-17"; |
| 26 | + const githubRepo = "FPGAwars/apio-dev-builds"; |
| 27 | + |
| 28 | +// Environment. Initialized on first call to ensureApioBinary |
| 29 | +let _apioBinDirPath = null; |
| 30 | +let _apioTmpDirPath = null; |
| 31 | +let _apioBinaryName = null; |
| 32 | +let _apioBinaryPath = null; |
| 33 | + |
| 34 | +// Initializes this module. Should be called once before any other |
| 35 | +// function of this module. |
| 36 | +function init() { |
| 37 | + // Should be called only once. |
| 38 | + assert( |
| 39 | + _apioBinDirPath == null, |
| 40 | + "apio-downloader.init() should be called at most once." |
| 41 | + ); |
| 42 | + |
| 43 | + // Get the absolute path to the user home dir. |
| 44 | + const homeDir = os.homedir(); |
| 45 | + apioLog.msg(`User home dir: ${homeDir}`); |
| 46 | + |
| 47 | + // Determine the absolute path of ~/.apio/tmp. We will |
| 48 | + // use it as a temporary storage of the downloaded package. |
| 49 | + _apioTmpDirPath = path.join(homeDir, ".apio", "tmp"); |
| 50 | + apioLog.msg(`Apio tmp dir: ${_apioTmpDirPath}`); |
| 51 | + |
| 52 | + // Determine the absolute path of ~/.apio/bin, this is |
| 53 | + // where we will store the apio binary and supporting files. |
| 54 | + _apioBinDirPath = path.join(homeDir, ".apio", "bin"); |
| 55 | + apioLog.msg(`Apio bin dir: ${_apioBinDirPath}`); |
| 56 | + |
| 57 | + // Determine apio binary name |
| 58 | + _apioBinaryName = platforms.isWindows() ? "apio.exe" : "apio"; |
| 59 | + |
| 60 | + // Determine the absolute path of the apio binary name. |
| 61 | + _apioBinaryPath = path.join(_apioBinDirPath, _apioBinaryName); |
| 62 | + apioLog.msg(`Apio binary path: ${_apioBinaryPath}`); |
| 63 | +} |
| 64 | + |
| 65 | +// Ensures the Apio binary is ready and if not download and installs it. |
| 66 | +// @returns {Promise<string>} with the path to apio / apio.exe |
| 67 | +async function ensureApioBinary() { |
| 68 | + // Check if the binary exists. |
| 69 | + const binaryOk = await _testFsItem( |
| 70 | + _apioBinaryPath, |
| 71 | + fs.constants.X_OK | fs.constants.R_OK |
| 72 | + ); |
| 73 | + |
| 74 | + if (binaryOk) { |
| 75 | + // Binary is good, will use it. |
| 76 | + apioLog.msg(`Apio binary found: ${_apioBinDirPath}`); |
| 77 | + } else { |
| 78 | + // Binary is missing or not good, will download and install it. |
| 79 | + apioLog.msg("Apio binary not found, will install."); |
| 80 | + await _downloadAndInstall(); |
| 81 | + } |
| 82 | + |
| 83 | + return _apioBinaryPath; |
| 84 | +} |
| 85 | + |
| 86 | +// Download the apio bundle and install it. |
| 87 | +// This async function returns a promise that govern the process. |
| 88 | +async function _downloadAndInstall() { |
| 89 | + |
| 90 | + const yyyymmdd = apioReleaseTag.replaceAll("-", ""); |
| 91 | + const platformId = platforms.getPlatformId(); |
| 92 | + const extension = platforms.isWindows() ? "zip" : "tgz"; |
| 93 | + |
| 94 | + const baseUrl = `https://github.com/${githubRepo}/releases/download/${apioReleaseTag}/`; |
| 95 | + const archiveName = `apio-${platformId}-${yyyymmdd}-bundle.${extension}`; |
| 96 | + const url = baseUrl + archiveName; |
| 97 | + const archivePath = path.join(_apioTmpDirPath, archiveName); |
| 98 | + |
| 99 | + apioLog.msg(`[Apio] Downloading: ${url}`); |
| 100 | + |
| 101 | + // Make the tmp dir if doesn't exist. |
| 102 | + await fs.promises.mkdir(_apioTmpDirPath, { recursive: true }); |
| 103 | + |
| 104 | + // Download the file to the tmp dir. |
| 105 | + await _downloadFile(url, archivePath); |
| 106 | + |
| 107 | + // Remove quarantine (macOS) from the archive. |
| 108 | + // |
| 109 | + // TODO: Do we really need this or is the bundle ok because we download |
| 110 | + // from VSCode? |
| 111 | + if (platforms.isDarwin()) { |
| 112 | + await new Promise((res) => { |
| 113 | + childProcess.exec( |
| 114 | + `xattr -d com.apple.quarantine "${archivePath}"`, |
| 115 | + (err) => { |
| 116 | + if (err) { |
| 117 | + console.warn("[Apio] Quarantine removal failed:", err.message); |
| 118 | + apioLog.msg("MacOS quarantine removal was not performed"); |
| 119 | + } else { |
| 120 | + console.log("[Apio] Quarantine removed"); |
| 121 | + apioLog.msg("MaxOS quarantine removal was performed"); |
| 122 | + } |
| 123 | + res(); |
| 124 | + } |
| 125 | + ); |
| 126 | + }); |
| 127 | + } |
| 128 | + |
| 129 | + // Extract |
| 130 | + if (archiveName.endsWith(".zip")) { |
| 131 | + await zipExtract(archivePath, { dir: _apioTmpDirPath }); |
| 132 | + } else if (archiveName.endsWith(".tgz")) { |
| 133 | + await tar.x({ file: archivePath, cwd: _apioTmpDirPath }); |
| 134 | + } |
| 135 | + |
| 136 | + // Clean up archive. We don't need it any more. |
| 137 | + await fs.promises.unlink(archivePath).catch(() => {}); |
| 138 | + |
| 139 | + // Expected: tmpDir/apio/ |
| 140 | + const extractedApioDir = path.join(_apioTmpDirPath, "apio"); |
| 141 | + // if (!(await fileExists(extractedApioDir))) { |
| 142 | + if (!(await _testFsItem(extractedApioDir))) { |
| 143 | + throw new Error('Archive did not contain "apio/" directory'); |
| 144 | + } |
| 145 | + |
| 146 | + // Ensure binDir exists, make an empty one if not. |
| 147 | + await fs.promises.mkdir(_apioBinDirPath, { recursive: true }); |
| 148 | + |
| 149 | + // Remove old binDir (overwrite) |
| 150 | + await fs.promises |
| 151 | + .rm(_apioBinDirPath, { recursive: true, force: true }) |
| 152 | + .catch(() => {}); |
| 153 | + |
| 154 | + // Move apio/ → binDir |
| 155 | + await fs.promises.rename(extractedApioDir, _apioBinDirPath); |
| 156 | + |
| 157 | + // const apioBinaryPath = path.join(_apioBinDirPath, ap); |
| 158 | + // if (!(await fileExists(_apioBinaryPath))) { |
| 159 | + if (!(await _testFsItem(_apioBinaryPath))) { |
| 160 | + throw new Error("Apio binary not found after extraction"); |
| 161 | + } |
| 162 | + |
| 163 | + // Make the apio binary executable |
| 164 | + if (!platforms.isWindows()) { |
| 165 | + await fs.promises.chmod(_apioBinaryPath, 0o755); |
| 166 | + } |
| 167 | +} |
| 168 | + |
| 169 | +// fetch is global in Node.js 18+ (no require needed at all!) |
| 170 | +async function _downloadFile(url, dest, maxRedirects = 5) { |
| 171 | + let currentUrl = url; |
| 172 | + let redirectsLeft = maxRedirects; |
| 173 | + |
| 174 | + while (redirectsLeft >= 0) { |
| 175 | + const res = await fetch(currentUrl, { |
| 176 | + headers: { |
| 177 | + "User-Agent": "vscode-apio-extension", |
| 178 | + Accept: "application/octet-stream", |
| 179 | + }, |
| 180 | + redirect: "manual", |
| 181 | + }); |
| 182 | + |
| 183 | + apioLog.msg(`HTTP ${res.status}`); |
| 184 | + |
| 185 | + if ( |
| 186 | + [301, 302, 303, 307, 308].includes(res.status) && |
| 187 | + res.headers.get("location") |
| 188 | + ) { |
| 189 | + currentUrl = new URL(res.headers.get("location"), currentUrl).href; |
| 190 | + apioLog.msg("URL redirect."); |
| 191 | + redirectsLeft--; |
| 192 | + continue; |
| 193 | + } |
| 194 | + |
| 195 | + if (res.status !== 200 || !res.body) { |
| 196 | + throw new Error(`HTTP error ${res.status}`); |
| 197 | + } |
| 198 | + |
| 199 | + // TODO: Move the require to the import and use here stream.promises.pipeline() |
| 200 | + // await require("node:stream/promises").pipeline(res.body, fs.createWriteStream(dest)); |
| 201 | + await stream.promises.pipeline(res.body, fs.createWriteStream(dest)); |
| 202 | + apioLog.msg(`Downloaded ${dest}`); |
| 203 | + return; |
| 204 | + } |
| 205 | + |
| 206 | + throw new Error("Too many redirects"); |
| 207 | +} |
| 208 | + |
| 209 | +// Similar to fs.promises.access but return true/false instead |
| 210 | +// of success/exception. |
| 211 | +async function _testFsItem(path, mode = fs.constants.F_OK) { |
| 212 | + try { |
| 213 | + await fs.promises.access(path, mode); |
| 214 | + return true; |
| 215 | + } catch { |
| 216 | + return false; |
| 217 | + } |
| 218 | +} |
| 219 | + |
| 220 | +/* ------------------------------------------------------------------ */ |
| 221 | +module.exports = { init, ensureApioBinary }; |
0 commit comments