diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml deleted file mode 100644 index a0adbaf..0000000 --- a/.github/workflows/test.yml +++ /dev/null @@ -1,25 +0,0 @@ -name: Test - -on: - push: - -jobs: - test: - name: Test on Multiple OS - runs-on: ${{ matrix.os }} - strategy: - matrix: - os: [ubuntu-latest, windows-latest, macos-latest] - steps: - - name: Checkout code - uses: actions/checkout@v3 - - name: Set up Deno - uses: denoland/setup-deno@v1 - with: - deno-version: v1.x - - name: setup StackQL - uses: stackql/setup-stackql@v2.0.0 - with: - use_wrapper: false - - name: Run tests - run: deno test --allow-net --allow-read --allow-write --allow-env --allow-run diff --git a/.gitignore b/.gitignore index f867e14..46f26a8 100644 --- a/.gitignore +++ b/.gitignore @@ -33,5 +33,4 @@ yarn-error.log* # typescript *.tsbuildinfo -next-env.d.ts -.stackql* \ No newline at end of file +next-env.d.ts \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json deleted file mode 100644 index 2c7ddc5..0000000 --- a/.vscode/settings.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "deno.enable": true, - "deno.lint": true, - "deno.unstable": true -} \ No newline at end of file diff --git a/README.md b/README.md index 0198492..4c0a490 100644 --- a/README.md +++ b/README.md @@ -18,11 +18,4 @@ - `upgrade` - if in local mode, upgrade the local stackql binary from the latest release - `execute` - execute a query returns an array of rows (objects) - `executeStmt` - executes a statement and returns a string (like `REGISTRY PULL` or `INSERT ...`) - - `executeQueriesAsync` - executes a list of queries and returns an array of rows (objects) - queries need to return the same columns/schema - -## Test -### Requirement -- To run the tests locally, [install StackQL](https://stackql.io/docs/installing-stackql) first. -``` - deno test --allow-net --allow-read --allow-write --allow-env --allow-run -``` \ No newline at end of file + - `executeQueriesAsync` - executes a list of queries and returns an array of rows (objects) - queries need to return the same columns/schema \ No newline at end of file diff --git a/deps.ts b/deps.ts index a837720..6cb0d37 100644 --- a/deps.ts +++ b/deps.ts @@ -1 +1 @@ -export { bold } from "https://deno.land/std/fmt/colors.ts" \ No newline at end of file +export { bold } from "https://deno.land/std@0.206.0/fmt/colors.ts"; \ No newline at end of file diff --git a/mod.ts b/mod.ts index 9ef3689..4236625 100644 --- a/mod.ts +++ b/mod.ts @@ -1,3 +1,5 @@ -import { StackQL } from "./src/stackql.ts"; +import { bold } from "./deps.ts"; -export { StackQL }; +export function getHelloWorld(): string { + return bold("Hello World"); + } diff --git a/src/services/downloader.test.ts b/src/services/downloader.test.ts deleted file mode 100644 index fc11f62..0000000 --- a/src/services/downloader.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { assertExists } from "https://deno.land/std@0.206.0/assert/assert_exists.ts"; -import { Downloader } from "./downloader.ts"; -import { removeStackQLDownload } from "../../testing/utils.ts"; -import { - assertSpyCalls, - spy, -} from "https://deno.land/std@0.207.0/testing/mock.ts"; - -Deno.test("Downloader setupStackQL and upgrade Test", async () => { - // Arrange - await removeStackQLDownload(); - const downloader = new Downloader(); - let binaryPath: string; - const denoOpenSpy = spy(Deno, "open"); - - // Act - const setupTest = async () => { - try { - binaryPath = await downloader.setupStackQL(); - - // Assert - assertExists(binaryPath); - assertSpyCalls(denoOpenSpy, 1); - // Check if the binary exists after setupStackQL is called - - console.log( - "Test passed: setupStackQL completed without errors and binary exists." - ); - } catch (error) { - console.error("Test failed:", error); - throw error; // This will cause the test to fail - } - }; - - const upgradeTest = async () => { - try { - binaryPath = await downloader.upgradeStackQL(); - - assertExists(binaryPath); - assertSpyCalls(denoOpenSpy, 2); - } catch (error) { - console.error("Test failed:", error); - throw error; // This will cause the test to fail - } - }; - - await setupTest(); - await upgradeTest(); -}); diff --git a/src/services/downloader.ts b/src/services/downloader.ts deleted file mode 100644 index 0e0246c..0000000 --- a/src/services/downloader.ts +++ /dev/null @@ -1,189 +0,0 @@ -import { join } from "https://deno.land/std@0.133.0/path/mod.ts"; -import { SupportedOs } from "../types/platforms.ts"; -import { darwinUnpack, unzip } from "./unpacker.ts"; -import osUtils from "../utils/os.ts"; - -export class Downloader { - private os: string; - private arch: string; - private urlMap: Record; - constructor() { - this.os = Deno.build.os; // 'linux', 'darwin', or 'windows' - this.arch = Deno.build.arch; // 'x86_64', 'arm64', etc. - - this.urlMap = { - [SupportedOs.Linux]: - "https://releases.stackql.io/stackql/latest/stackql_linux_amd64.zip", - [SupportedOs.Windows]: - "https://releases.stackql.io/stackql/latest/stackql_windows_amd64.zip", - [SupportedOs.Darwin]: - "https://storage.googleapis.com/stackql-public-releases/latest/stackql_darwin_multiarch.pkg", - // Additional OS-architecture combinations can be added here - }; - } - - private async downloadFile(url: string, downloadDir: string) { - const res = await fetch(url); - // create dir if not exists - - const file = await Deno.open(downloadDir, { create: true, write: true }); - - try { - await res.body?.pipeTo(file.writable).finally( - () => file.close() //TODO: fix bad resource id when closing file - ); - } catch (error) { - console.error(`ERROR: [downloadFile] ${error.message}`); - } - - console.log("Closed file"); - } - - private getUrl(): string { - const key = `${this.os}`; - const url = this.urlMap[key]; - - if (!url) { - throw new Error(`Unsupported OS type: ${this.os}`); - } - - return url; - } - - /** - * Gets binary name - * @returns binrary name - */ - private getBinaryName() { - const binaryMap: Record = { - [SupportedOs.Windows]: "stackql.exe", - [SupportedOs.Darwin]: "stackql/Payload/stackql", - [SupportedOs.Linux]: "stackql", // Default case for Linux and other platforms - }; - const os = Deno.build.os.toLowerCase(); - - if (!Object.values(SupportedOs).includes(os as SupportedOs)) { - throw new Error(`Unsupported OS type: ${os}`); - } - - const binaryOs = os as SupportedOs; - return binaryMap[binaryOs]; - } - - private async createDownloadDir(downloadDir: string) { - try { - const stat = await Deno.stat(downloadDir); - if (!stat.isDirectory) { - await Deno.mkdir(downloadDir, { recursive: true }); - } - } catch (error) { - if (error instanceof Deno.errors.NotFound) { - await Deno.mkdir(downloadDir, { recursive: true }); - } else { - throw error; - } - } - } - /** - * Gets download dir - * @returns download dir - */ - private getDownloadDir(): string { - const projectDir = Deno.cwd(); - - if (!projectDir) { - throw new Error("Unable to determine the project directory."); - } - - const downloadDir = join(projectDir, ".stackql"); - - return downloadDir; - } - - private binaryExists(binaryName: string, downloadDir: string): boolean { - const binPath = join(downloadDir, binaryName); - try { - Deno.statSync(binPath); - return true; - } catch (error) { - if (error instanceof Deno.errors.NotFound) { - return false; - } - throw error; - } - } - private async installStackQL(downloadDir: string) { - const url = this.getUrl(); - - const archiveFileName = `${downloadDir}/${url.split("/").pop()}`; - await this.downloadFile(url, archiveFileName); - - console.log("Unpacking stackql binary"); - const unpacker = Deno.build.os === "darwin" ? darwinUnpack : unzip; - await unpacker({ downloadDir, archiveFileName }); - } - - private async setExecutable(binaryPath: string) { - const allowExecOctal = 0o755; - await osUtils.chomod(binaryPath, allowExecOctal); - } - - private async downloadAndInstallStackQL({ - downloadDir, - binaryName, - }: { - downloadDir: string; - binaryName: string; - }) { - const binaryPath = join(downloadDir, binaryName); - await this.installStackQL(downloadDir); - await this.setExecutable(binaryPath); - return binaryPath; - } - /** - * Setup stackql binary, check if binary exists, if not download it - */ - public async setupStackQL() { - try { - const binaryName = this.getBinaryName(); - const downloadDir = this.getDownloadDir(); - await this.createDownloadDir(downloadDir); - - let binaryPath = join(downloadDir, binaryName); - - if (this.binaryExists(binaryName, downloadDir)) { - await this.setExecutable(binaryPath); - return binaryPath; - } - - binaryPath = await this.downloadAndInstallStackQL({ - downloadDir, - binaryName, - }); - return binaryPath; - } catch (error) { - console.error(`ERROR: [setup] ${error.message}`); - Deno.exit(1); - } - } - - private async removeStackQL() { - const downloadDir = this.getDownloadDir(); - await Deno.remove(join(downloadDir, "/"), { recursive: true }); - console.log("stackql download dir removed"); - } - - public async upgradeStackQL() { - if (Deno.build.os === "darwin") { - await this.removeStackQL(); - } - const binaryName = this.getBinaryName(); - const downloadDir = this.getDownloadDir(); - await this.createDownloadDir(downloadDir); - const binaryPath = await this.downloadAndInstallStackQL({ - downloadDir, - binaryName, - }); - return binaryPath; - } -} diff --git a/src/services/server.test.ts b/src/services/server.test.ts deleted file mode 100644 index 30f31a9..0000000 --- a/src/services/server.test.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { Server } from "./server.ts"; -import { assert } from "https://deno.land/std@0.207.0/assert/assert.ts"; -import { startStackQLServer } from "../../testing/utils.ts"; - -Deno.test("Successful Connection", async () => { - const { closeProcess } = await startStackQLServer(); - const server = new Server(); - const pg = await server.connect( - "postgres://postgres:password@localhost:5444/postgres", - ); - assert(pg); - await server.close(); - await closeProcess(); -}); diff --git a/src/services/server.ts b/src/services/server.ts deleted file mode 100644 index 813be33..0000000 --- a/src/services/server.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { Client } from "https://deno.land/x/postgres/mod.ts"; - -export class Server { - private client: Client | null = null; - - constructor(connectionString?: string) { - if (connectionString) { - this.client = new Client(connectionString); - } - } - - public async connect(connectionString?: string) { - const maxRetries = 3; - let currentAttempt = 0; - - while (currentAttempt < maxRetries) { - try { - const connection = Deno.env.get("POSTGRES") || connectionString; - if (!connection) { - throw new Error( - "Connection string not found \n Please set the POSTGRES environment variable or pass the connection string as an argument", - ); - } - - console.log("connecting", connection); - this.client = new Client(connection); - await this.client.connect(); - console.log("connected"); - return this.client; - } catch (error) { - currentAttempt++; - console.log(`Attempt ${currentAttempt} failed: ${error.message}`); - - if (currentAttempt >= maxRetries) { - throw new Error( - `Could not connect to the server after ${maxRetries} attempts: ${error.message}`, - ); - } - - // Wait for 1 second before the next attempt - await new Promise((resolve) => setTimeout(resolve, 1000)); - } - } - } - - public async close() { - if (this.client) { - await this.client.end(); - } - } - - // Additional methods for query execution can be added here -} diff --git a/src/services/unpacker.ts b/src/services/unpacker.ts deleted file mode 100644 index 25961d0..0000000 --- a/src/services/unpacker.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { decompress } from "https://deno.land/x/zip/mod.ts"; - -type UnpackParams = { - downloadDir: string; - archiveFileName: string; -}; - -export const darwinUnpack = async (params: UnpackParams) => { - console.log("darwinUnpack"); - const { downloadDir, archiveFileName } = params; - const unpackedFileName = `${downloadDir}/stackql`; - const commandPath = "pkgutil"; - const commandArgs = ["--expand-full", archiveFileName, unpackedFileName]; - const process = new Deno.Command(commandPath, { - args: commandArgs, - stdout: "piped", - stderr: "piped", - }); - - const { code, stdout, stderr } = await process.output(); - if (code !== 0) { - const output = new TextDecoder().decode(stdout); - const errorOutput = new TextDecoder().decode(stderr); - console.error("Error executing pkgutil:", output, errorOutput); - throw new Error("Failed to unpack stackql"); - } -}; - -export const unzip = async (params: UnpackParams) => { - console.log("unzip"); - try { - await decompress(params.archiveFileName, params.downloadDir); - } catch (error) { - console.log("[unzip] error:", error); - throw new Error("Failed to unpack stackql"); - } -}; diff --git a/src/stackql.test.ts b/src/stackql.test.ts deleted file mode 100644 index 4462c1c..0000000 --- a/src/stackql.test.ts +++ /dev/null @@ -1,210 +0,0 @@ -import { assertStringIncludes } from "https://deno.land/std@0.206.0/assert/mod.ts"; -import { StackQL } from "./stackql.ts"; -import { startStackQLServer } from "../testing/utils.ts"; -import { - assertEquals, - assertExists, -} from "https://deno.land/std@0.160.0/testing/asserts.ts"; -import { Downloader } from "./services/downloader.ts"; -import { - assertSpyCall, - spy, -} from "https://deno.land/std@0.207.0/testing/mock.ts"; -import osUtils from "./utils/os.ts"; -import { assert } from "https://deno.land/std@0.133.0/_util/assert.ts"; - -const downloader = new Downloader(); - -const setupStackQL = async () => { - await downloader.setupStackQL(); -}; - -Deno.test("StackQL CLI run query", async () => { - await setupStackQL(); - - // Arrange - const stackQL = new StackQL(); - await stackQL.initialize({ serverMode: false }); - - const pullQuery = "REGISTRY PULL github;"; - const providerQuery = "SHOW PROVIDERS"; - const githubTestQuery = - `SELECT id, name from github.repos.repos where org='stackql'`; - - // Act - await stackQL.runQuery(pullQuery); - const result = await stackQL.runQuery(providerQuery); - const githubResult = await stackQL.runQuery(githubTestQuery); - - // Assert - assertStringIncludes(result, "name"); - assertStringIncludes(result, "version"); - assertStringIncludes(result, "github"); - assertStringIncludes(githubResult, "stackql"); -}); - -Deno.test("Set properties from configs", async () => { - await setupStackQL(); - const runCliSpy = spy(osUtils, "runCommand"); - const stackQL = new StackQL(); - await stackQL.initialize({ - serverMode: false, - maxResults: 100, - pageLimit: 10, - maxDepth: 5, - apiTimeout: 5000, - }); - const githubTestQuery = - `SELECT id, name from github.repos.repos where org='stackql'`; - - await stackQL.runQuery(githubTestQuery); - - const params = stackQL.getParams(); - assertEquals(params.length, 8); - assertEquals(params, [ - "--http.response.maxResults", - "100", - "--http.response.pageLimit", - "10", - "--indirect.depth.max", - "5", - "--apirequesttimeout", - "5000", - ]); - const binaryPath = stackQL.getBinaryPath(); - assert(binaryPath); - assertSpyCall(runCliSpy, 0, { - args: [binaryPath, ["exec", githubTestQuery, ...params]], - }); - runCliSpy.restore(); -}); - -Deno.test("Set proxy properties from configs", async () => { - await setupStackQL(); - const runCommandSpy = spy(osUtils, "runCommand"); - const stackQL = new StackQL(); - await stackQL.initialize({ - serverMode: false, - proxyHost: "localhost", - proxyPort: 8080, - proxyUser: "user", - proxyPassword: "password", - proxyScheme: "https", - }); - const githubTestQuery = - `SELECT id, name from github.repos.repos where org='stackql'`; - - await stackQL.runQuery(githubTestQuery); - - const params = stackQL.getParams(); - assertEquals(params, [ - "--http.proxy.host", - "localhost", - "--http.proxy.port", - "8080", - "--http.proxy.user", - "user", - "--http.proxy.password", - "password", - "--http.proxy.scheme", - "https", - ]); - const binaryPath = stackQL.getBinaryPath(); - assert(binaryPath); - assertSpyCall(runCommandSpy, 0, { - args: [binaryPath, ["exec", githubTestQuery, ...params]], - }); - runCommandSpy.restore(); -}); - -Deno.test("StackQL runServerQuery", async () => { - const { closeProcess } = await startStackQLServer(); - const stackQL = new StackQL(); - - try { - // Arrange - await stackQL.initialize({ - serverMode: true, - connectionString: "postgres://postgres:password@localhost:5444/postgres", - }); - const pullQuery = "REGISTRY PULL github;"; - const testQuery = "SHOW SERVICES IN github LIKE '%repos%';"; // Replace with a valid query for your context - - // Act - await stackQL.runServerQuery(pullQuery); - const results = await stackQL.runServerQuery(testQuery); - assertExists(results); - assertEquals(results.length, 1); - const result = results[0] as { - name: string; - }; - assertEquals(result.name, "repos"); - - // Assert - } finally { - // Cleanup - await closeProcess(); - await stackQL.closeConnection(); - } -}); - -Deno.test("getVersion", async () => { - await setupStackQL(); - const stackQL = new StackQL(); - await stackQL.initialize({ serverMode: false }); - const versionRegex = /^v?(\d+(?:\.\d+)*)$/; - const shaRegex = /^[a-f0-9]{7}$/; - - const { version, sha } = await stackQL.getVersion(); - - assert(version); - assert(sha); - assert(versionRegex.test(version)); - assert(shaRegex.test(sha)); -}); - -Deno.test("getVersion when version and sha are undefined", async () => { - await setupStackQL(); - const stackQL = new StackQL(); - await stackQL.initialize({ serverMode: false }); - const versionRegex = /^v?(\d+(?:\.\d+)*)$/; - const shaRegex = /^[a-f0-9]{7}$/; - // deno-lint-ignore no-explicit-any - (stackQL as any).version = undefined; - // deno-lint-ignore no-explicit-any - (stackQL as any).sha = undefined; - // deno-lint-ignore no-explicit-any - assert((stackQL as any).version === undefined); - // deno-lint-ignore no-explicit-any - assert((stackQL as any).sha === undefined); - - const { version, sha } = await stackQL.getVersion(); - - assert(version); - assert(sha); - assert(versionRegex.test(version)); - assert(shaRegex.test(sha)); -}); - -Deno.test("upgrade stackql", async () => { - await setupStackQL(); - const stackQL = new StackQL(); - await stackQL.initialize({ serverMode: false }); - // deno-lint-ignore no-explicit-any - (stackQL as any).version = undefined; - // deno-lint-ignore no-explicit-any - (stackQL as any).sha = undefined; - const versionRegex = /^v?(\d+(?:\.\d+)*)$/; - const shaRegex = /^[a-f0-9]{7}$/; - // deno-lint-ignore no-explicit-any - assert((stackQL as any).version === undefined); - // deno-lint-ignore no-explicit-any - assert((stackQL as any).sha === undefined); - - const { version, sha } = await stackQL.upgrade(); - - assert(version); - assert(sha); - assert(versionRegex.test(version)); - assert(shaRegex.test(sha)); -}); diff --git a/src/stackql.ts b/src/stackql.ts deleted file mode 100644 index a7ae4eb..0000000 --- a/src/stackql.ts +++ /dev/null @@ -1,185 +0,0 @@ -import { assertExists } from "https://deno.land/std@0.206.0/assert/assert_exists.ts"; -import { Downloader } from "./services/downloader.ts"; -import osUtils from "./utils/os.ts"; -import { Server } from "./services/server.ts"; -import { Client } from "https://deno.land/x/postgres@v0.17.0/client.ts"; - -export interface StackQLConfig { - binaryPath?: string; - serverMode?: boolean; - connectionString?: string; - maxResults?: number; - pageLimit?: number; - maxDepth?: number; - apiTimeout?: number; - proxyHost?: string; - proxyPort?: number; - proxyUser?: string; - proxyPassword?: string; - proxyScheme?: "http" | "https"; -} - -export class StackQL { - private binaryPath?: string; //The full path of the `stackql` executable (not supported in `server_mode`). - private downloader: Downloader = new Downloader(); - private serverMode = false; - private connection?: Client; - private format: "object" = "object"; - private params: string[] = []; - private version: string | undefined; // The version number of the `stackql` executable (not supported in `server_mode`) - private sha: string | undefined; // The commit (short) sha for the installed `stackql` binary build (not supported in `server_mode`). - constructor() { - } - - getParams() { - return this.params; - } - - getBinaryPath() { - return this.binaryPath; - } - - async getVersion() { - if (!this.version) { - await this.updateVersion(); - } - - return { version: this.version, sha: this.sha }; - } - - private async updateVersion() { - if (!this.binaryPath) { - throw new Error("Binary path not found"); - } - const output = await osUtils.runCommand(this.binaryPath, ["--version"]); - if (output) { - const versionTokens: string[] = output.split("\n")[0].split(" "); - const version: string = versionTokens[1]; - const sha: string = versionTokens[3].replace("(", "").replace(")", ""); - - this.version = version; - this.sha = sha; - } - } - async upgrade() { - this.binaryPath = await this.downloader.upgradeStackQL(); - await this.updateVersion(); - return this.getVersion(); - } - - public async initialize(config: StackQLConfig) { - this.binaryPath = config.binaryPath; - this.serverMode = config.serverMode || false; - if (this.serverMode) { - await this.setupConnection(config.connectionString); - return; - } - if (this.binaryExist()) { - return; - } - this.binaryPath = await this.downloader.setupStackQL(); - this.setProperties(config); - } - private binaryExist() { - return !!this.binaryPath && osUtils.fileExists(this.binaryPath); - } - private setProxyProperties(config: StackQLConfig): void { - if (config.proxyHost !== undefined) { - this.params.push("--http.proxy.host"); - this.params.push(config.proxyHost); - } - - if (config.proxyPort !== undefined) { - this.params.push("--http.proxy.port"); - this.params.push(config.proxyPort.toString()); - } - - if (config.proxyUser !== undefined) { - this.params.push("--http.proxy.user"); - this.params.push(config.proxyUser); - } - - if (config.proxyPassword !== undefined) { - this.params.push("--http.proxy.password"); - this.params.push(config.proxyPassword); - } - - if (config.proxyScheme !== undefined) { - if (!["http", "https"].includes(config.proxyScheme)) { - throw new Error( - `Invalid proxyScheme. Expected one of ['http', 'https'], got ${config.proxyScheme}.`, - ); - } - this.params.push("--http.proxy.scheme"); - this.params.push(config.proxyScheme); - } - } - - private setProperties(config: StackQLConfig): void { - if (config.maxResults !== undefined) { - this.params.push("--http.response.maxResults"); - this.params.push(config.maxResults.toString()); - } - - if (config.pageLimit !== undefined) { - this.params.push("--http.response.pageLimit"); - this.params.push(config.pageLimit.toString()); - } - - if (config.maxDepth !== undefined) { - this.params.push("--indirect.depth.max"); - this.params.push(config.maxDepth.toString()); - } - - if (config.apiTimeout !== undefined) { - this.params.push("--apirequesttimeout"); - this.params.push(config.apiTimeout.toString()); - } - - if (config.proxyHost !== undefined) { - this.setProxyProperties(config); - } - } - - public async runQuery(query: string) { - assertExists(this.binaryPath); - const args = ["exec", query].concat(this.params); - try { - const result = await osUtils.runCommand(this.binaryPath, args); - return result; - } catch (error) { - console.error(error); - throw new Error(`StackQL query failed: ${error.message}`); - } - } - - //////////////////////Server mode related methods - private async queryObjectFormat(query: string) { - assertExists(this.connection); - const pgResult = await this.connection.queryObject(query); - return pgResult.rows; - } - - private async setupConnection(connectionString?: string) { - const server = new Server(); - this.connection = await server.connect(connectionString); - } - - public async closeConnection() { - if (this.connection) { - await this.connection.end(); - } - } - - public async runServerQuery(query: string) { - try { - if (this.format === "object") { - const result = await this.queryObjectFormat(query); - return result; - } - } catch (error) { - console.error(error); - throw new Error(`StackQL server query failed: ${error.message}`); - } - } -} diff --git a/src/types/platforms.ts b/src/types/platforms.ts deleted file mode 100644 index 8948c55..0000000 --- a/src/types/platforms.ts +++ /dev/null @@ -1,5 +0,0 @@ -export enum SupportedOs { - Linux = "linux", - Darwin = "darwin", - Windows = "windows", -} \ No newline at end of file diff --git a/src/utils/os.test.ts b/src/utils/os.test.ts deleted file mode 100644 index 1183499..0000000 --- a/src/utils/os.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { - assertRejects, - assertStringIncludes, -} from "https://deno.land/std@0.160.0/testing/asserts.ts"; -import osUtils from "./os.ts"; - -Deno.test("osUtils.runCommand: Test Successful Execution", async () => { - const command = Deno.build.os === "windows" ? "cmd" : "echo"; - const args = Deno.build.os === "windows" - ? ["/c", "echo", "Hello, World!"] - : ["Hello, World!"]; - const result = await osUtils.runCommand(command, args); - assertStringIncludes(result.trim(), "Hello, World!"); -}); - -Deno.test("osUtils.runCommand: Test Failed Execution", () => { - const command = "invalid"; - const args = Deno.build.os === "windows" - ? ["/c", "echo", "Hello, World!"] - : ["Hello, World!"]; - assertRejects(async () => { - await osUtils.runCommand(command, args); - }); -}); diff --git a/src/utils/os.ts b/src/utils/os.ts deleted file mode 100644 index 29d3f5d..0000000 --- a/src/utils/os.ts +++ /dev/null @@ -1,48 +0,0 @@ -const fileExists = (path?: string) => { - if (!path) { - return false; - } - try { - Deno.statSync(path); - return true; - } catch (error) { - if (error instanceof Deno.errors.NotFound) { - return false; - } - throw error; - } -}; - -const chomod = async (path: string, mode: number) => { - if (Deno.build.os !== "windows") { - await Deno.chmod(path, mode); - } -}; - -const runCommand = async (path: string, args: string[]) => { - const process = new Deno.Command(path, { - args, - stdout: "piped", - stderr: "piped", - }); - - const { code, stdout, stderr } = await process.output(); - - if (code === 0) { - const output = stdout; - const result = new TextDecoder().decode(output); - return result; - } else { - const errorOutput = stderr; - const errorMessage = new TextDecoder().decode(errorOutput); - throw new Error(errorMessage); - } -}; - -const osUtils = { - fileExists, - chomod, - runCommand, -}; - -export default osUtils; diff --git a/testing/utils.ts b/testing/utils.ts deleted file mode 100644 index 88f8463..0000000 --- a/testing/utils.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { existsSync } from "https://deno.land/std/fs/mod.ts"; -import { join } from "https://deno.land/std@0.133.0/path/mod.ts"; - -export const removeStackQLDownload = async () => { - const projectDir = Deno.cwd(); - const stackqlPath = join(projectDir, ".stackql"); - console.log("stackqlPath", stackqlPath); - console.log("existsSync(stackqlPath)", existsSync(stackqlPath)); - if (existsSync(stackqlPath)) { - console.log("Removing .stackql directory"); - await Deno.remove(stackqlPath, { recursive: true }); - } -}; - -export const startStackQLServer = async (port = 5444) => { - const command = new Deno.Command("stackql", { - args: [ - "srv", - "--pgsrv.address=0.0.0.0", - `--pgsrv.port=${port}`, - ], - stdout: "inherit", - stderr: "inherit", - }); - const process = command.spawn(); - //TODO: find a way to wait for the server to be ready - const closeProcess = async () => { - try { - console.log("Closing process"); - process.kill(); - await process.status; - } catch (error) { - const alreadyClosed = error.message.includes( - "Child process has already terminated", - ); - if (alreadyClosed) { - console.log("Process already closed"); - return; - } - throw error; - } - }; - return { closeProcess }; -};