| 1 | import { Process } from "@withfig/api-bindings"; |
| 2 | import { useEffect, useState } from "react"; |
| 3 | |
| 4 | type ExecuteCommandOutput = |
| 5 | | { |
| 6 | status: "loading"; |
| 7 | } |
| 8 | | { |
| 9 | status: "success"; |
| 10 | exitCode: number; |
| 11 | stdout: string; |
| 12 | stderr: string; |
| 13 | } |
| 14 | | { |
| 15 | status: "error"; |
| 16 | error: Error; |
| 17 | }; |
| 18 | |
| 19 | export const useExecuteCommand = ( |
| 20 | input: { command: string } | { args: string[] } |
| 21 | ): ExecuteCommandOutput => { |
| 22 | let executable: string; |
| 23 | let args: string[]; |
| 24 | if ("command" in input && input.command) { |
| 25 | executable = "bash"; |
| 26 | args = ["-c", input.command]; |
| 27 | } else if ("args" in input && input.args.length > 0) { |
| 28 | // eslint-disable-next-line prefer-destructuring |
| 29 | executable = input.args[0]; |
| 30 | args = input.args.slice(1); |
| 31 | } else { |
| 32 | throw new Error("Invalid input"); |
| 33 | } |
| 34 | |
| 35 | const [output, setOutput] = useState<ExecuteCommandOutput>({ |
| 36 | status: "loading", |
| 37 | }); |
| 38 | |
| 39 | useEffect(() => { |
| 40 | Process.run({ |
| 41 | executable, |
| 42 | args, |
| 43 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment |
| 44 | // @ts-ignore |
| 45 | terminalSessionId: window?.globalTerminalSessionId, |
| 46 | }) |
| 47 | .then(({ exitCode, stderr, stdout }) => { |
| 48 | setOutput({ |
| 49 | status: "success", |
| 50 | exitCode, |
| 51 | stderr, |
| 52 | stdout, |
| 53 | }); |
| 54 | }) |
| 55 | .catch((error) => { |
| 56 | setOutput({ |
| 57 | status: "error", |
| 58 | error, |
| 59 | }); |
| 60 | }); |
| 61 | }, [executable, args]); |
| 62 | |
| 63 | return output; |
| 64 | }; |