Philipp Schrader | 272e07b | 2024-03-29 17:26:02 -0700 | [diff] [blame] | 1 | // This script acts as a wrapper for the `foxglove-extension` binary. We need a |
| 2 | // wrapper here because `foxglove-extension` wants to invoke `npm` directly. |
| 3 | // Since we don't support the real npm binary, we force `foxglove-extension` to |
| 4 | // use our fake npm binary (`foxglove_extension_wrapper_npm.js`) by |
| 5 | // manipulating the PATH. |
| 6 | |
| 7 | const { spawnSync } = require('child_process'); |
| 8 | const path = require('path'); |
| 9 | const process = require('process'); |
| 10 | const fs = require('fs'); |
| 11 | const { tmpdir } = require('os'); |
| 12 | |
| 13 | // Add a directory to the PATH environment variable. |
| 14 | function addToPath(directory) { |
| 15 | const currentPath = process.env.PATH || ''; |
| 16 | const newPath = `${directory}${path.delimiter}${currentPath}`; |
| 17 | process.env.PATH = newPath; |
| 18 | } |
| 19 | |
| 20 | const fakeNpm = path.join(__dirname, 'foxglove_extension_wrapper_npm.sh'); |
| 21 | |
| 22 | const tempBinDir = fs.mkdtempSync(path.join(tmpdir(), "foxglove_extension_wrapper-tmp-")); |
| 23 | fs.symlinkSync(fakeNpm, path.join(tempBinDir, 'npm')); |
| 24 | |
| 25 | addToPath(tempBinDir); |
| 26 | |
| 27 | // Create a relative path for a specific root-relative directory. |
| 28 | function getRelativePath(filePath) { |
| 29 | // Count the number of directories and construct the relative path. |
| 30 | const numDirectories = filePath.split('/').length; |
| 31 | return '../'.repeat(numDirectories); |
| 32 | } |
| 33 | |
| 34 | // We need to know the path to the `foxglove-extension` binary from the |
| 35 | // sub-directory where we're generating code into. |
| 36 | const relativePath = getRelativePath(process.env.BAZEL_PACKAGE); |
| 37 | const foxgloveExtensionPath = path.join(relativePath, `tools/foxglove/foxglove_extension.sh`) |
| 38 | |
| 39 | // Extract arguments intended for the `foxglove-extension` binary. |
| 40 | const args = process.argv.slice(2); |
| 41 | |
| 42 | // Execute the `foxglove-extension` binary. |
| 43 | try { |
| 44 | const result = spawnSync(foxgloveExtensionPath, args, { stdio: 'inherit', cwd: process.env.BAZEL_PACKAGE }); |
| 45 | if (result.error) { |
| 46 | console.error('Error executing foxglove_extension:', result.error); |
| 47 | process.exit(1); |
| 48 | } |
| 49 | if (result.status !== 0) { |
| 50 | console.error(`foxglove_extension exited with status ${result.status}`); |
| 51 | process.exit(result.status); |
| 52 | } |
| 53 | } catch (error) { |
| 54 | console.error('Error executing foxglove_extension:', error); |
| 55 | process.exit(1); |
| 56 | } |