From 2d7283e89d32d6be59cb1adcecc7473370fd4486 Mon Sep 17 00:00:00 2001 From: Julian Date: Tue, 18 Mar 2025 08:20:19 +0100 Subject: [PATCH 1/3] chore: rename pglt in packages/ --- packages/@pglt/backend-jsonrpc/package.json | 32 -- packages/@pglt/backend-jsonrpc/src/command.ts | 36 -- .../@pglt/backend-jsonrpc/src/workspace.ts | 453 ------------------ .../backend-jsonrpc/tests/workspace.test.mjs | 54 --- packages/@pglt/pglt/package.json | 40 -- .../@pglt/pglt/scripts/generate-packages.mjs | 250 ---------- .../backend-jsonrpc/package.json | 38 ++ .../backend-jsonrpc/src/command.ts | 36 ++ .../backend-jsonrpc/src/index.ts | 32 +- .../backend-jsonrpc/src/socket.ts | 0 .../backend-jsonrpc/src/transport.ts | 0 .../backend-jsonrpc/src/workspace.ts | 453 ++++++++++++++++++ .../backend-jsonrpc/tests/transport.test.mjs | 0 .../backend-jsonrpc/tests/workspace.test.mjs | 54 +++ .../postgrestools}/bin/pglt | 16 +- .../@postgrestools/postgrestools/package.json | 43 ++ .../scripts/generate-packages.mjs | 256 ++++++++++ 17 files changed, 904 insertions(+), 889 deletions(-) delete mode 100644 packages/@pglt/backend-jsonrpc/package.json delete mode 100644 packages/@pglt/backend-jsonrpc/src/command.ts delete mode 100644 packages/@pglt/backend-jsonrpc/src/workspace.ts delete mode 100644 packages/@pglt/backend-jsonrpc/tests/workspace.test.mjs delete mode 100644 packages/@pglt/pglt/package.json delete mode 100644 packages/@pglt/pglt/scripts/generate-packages.mjs create mode 100644 packages/@postgrestools/backend-jsonrpc/package.json create mode 100644 packages/@postgrestools/backend-jsonrpc/src/command.ts rename packages/{@pglt => @postgrestools}/backend-jsonrpc/src/index.ts (68%) rename packages/{@pglt => @postgrestools}/backend-jsonrpc/src/socket.ts (100%) rename packages/{@pglt => @postgrestools}/backend-jsonrpc/src/transport.ts (100%) create mode 100644 packages/@postgrestools/backend-jsonrpc/src/workspace.ts rename packages/{@pglt => @postgrestools}/backend-jsonrpc/tests/transport.test.mjs (100%) create mode 100644 packages/@postgrestools/backend-jsonrpc/tests/workspace.test.mjs rename packages/{@pglt/pglt => @postgrestools/postgrestools}/bin/pglt (50%) create mode 100644 packages/@postgrestools/postgrestools/package.json create mode 100644 packages/@postgrestools/postgrestools/scripts/generate-packages.mjs diff --git a/packages/@pglt/backend-jsonrpc/package.json b/packages/@pglt/backend-jsonrpc/package.json deleted file mode 100644 index 838f796c5..000000000 --- a/packages/@pglt/backend-jsonrpc/package.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "@pglt/backend-jsonrpc", - "version": "", - "main": "dist/index.js", - "scripts": { - "test": "bun test", - "test:ci": "bun build && bun test", - "build": "bun build ./src/index.ts --outdir ./dist --target node" - }, - "files": ["dist/", "README.md"], - "repository": { - "type": "git", - "url": "git+https://github.com/supabase-community/postgres_lsp.git", - "directory": "packages/@pglt/backend-jsonrpc" - }, - "author": "Supabase Community", - "bugs": "ttps://github.com/supabase-community/postgres_lsp/issues", - "description": "Bindings to the JSON-RPC Workspace API of the Postgres Language Tools daemon", - "keywords": ["TypeScript", "Postgres"], - "license": "MIT", - "publishConfig": { - "provenance": true - }, - "optionalDependencies": { - "@pglt/cli-win32-x64": "", - "@pglt/cli-win32-arm64": "", - "@pglt/cli-darwin-x64": "", - "@pglt/cli-darwin-arm64": "", - "@pglt/cli-linux-x64": "", - "@pglt/cli-linux-arm64": "" - } -} diff --git a/packages/@pglt/backend-jsonrpc/src/command.ts b/packages/@pglt/backend-jsonrpc/src/command.ts deleted file mode 100644 index 7249002e5..000000000 --- a/packages/@pglt/backend-jsonrpc/src/command.ts +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Gets the path of the binary for the current platform - * - * @returns Filesystem path to the binary, or null if no prebuilt distribution exists for the current platform - */ -export function getCommand(): string | null { - const { platform, arch } = process; - - type PlatformPaths = { - [P in NodeJS.Platform]?: { - [A in NodeJS.Architecture]?: string; - }; - }; - - const PLATFORMS: PlatformPaths = { - win32: { - x64: "@pglt/cli-win32-x64/pglt.exe", - arm64: "@pglt/cli-win32-arm64/pglt.exe", - }, - darwin: { - x64: "@pglt/cli-darwin-x64/pglt", - arm64: "@pglt/cli-darwin-arm64/pglt", - }, - linux: { - x64: "@pglt/cli-linux-x64/pglt", - arm64: "@pglt/cli-linux-arm64/pglt", - }, - }; - - const binPath = PLATFORMS?.[platform]?.[arch]; - if (!binPath) { - return null; - } - - return require.resolve(binPath); -} diff --git a/packages/@pglt/backend-jsonrpc/src/workspace.ts b/packages/@pglt/backend-jsonrpc/src/workspace.ts deleted file mode 100644 index c110b0ef9..000000000 --- a/packages/@pglt/backend-jsonrpc/src/workspace.ts +++ /dev/null @@ -1,453 +0,0 @@ -// Generated file, do not edit by hand, see `xtask/codegen` -import type { Transport } from "./transport"; -export interface IsPathIgnoredParams { - pglt_path: PgLTPath; -} -export interface PgLTPath { - /** - * Determines the kind of the file inside PgLT. Some files are considered as configuration files, others as manifest files, and others as files to handle - */ - kind: FileKind; - path: string; - /** - * Whether this path (usually a file) was fixed as a result of a format/lint/check command with the `--write` filag. - */ - was_written: boolean; -} -export type FileKind = FileKind2[]; -/** - * The priority of the file - */ -export type FileKind2 = "Config" | "Ignore" | "Inspectable" | "Handleable"; -export interface GetFileContentParams { - path: PgLTPath; -} -export interface PullDiagnosticsParams { - categories: RuleCategories; - max_diagnostics: number; - only: RuleCode[]; - path: PgLTPath; - skip: RuleCode[]; -} -export type RuleCategories = RuleCategory[]; -export type RuleCode = string; -export type RuleCategory = "Lint" | "Action" | "Transformation"; -export interface PullDiagnosticsResult { - diagnostics: Diagnostic[]; - errors: number; - skipped_diagnostics: number; -} -/** - * Serializable representation for a [Diagnostic](super::Diagnostic). - */ -export interface Diagnostic { - advices: Advices; - category?: Category; - description: string; - location: Location; - message: MarkupBuf; - severity: Severity; - source?: Diagnostic; - tags: DiagnosticTags; - verboseAdvices: Advices; -} -/** - * Implementation of [Visitor] collecting serializable [Advice] into a vector. - */ -export interface Advices { - advices: Advice[]; -} -export type Category = - | "lint/safety/addingRequiredField" - | "lint/safety/banDropColumn" - | "lint/safety/banDropNotNull" - | "lint/safety/banDropTable" - | "stdin" - | "check" - | "configuration" - | "database/connection" - | "internalError/io" - | "internalError/runtime" - | "internalError/fs" - | "flags/invalid" - | "project" - | "typecheck" - | "internalError/panic" - | "syntax" - | "dummy" - | "lint" - | "lint/performance" - | "lint/safety"; -export interface Location { - path?: Resource_for_String; - sourceCode?: string; - span?: TextRange; -} -export type MarkupBuf = MarkupNodeBuf[]; -/** - * The severity to associate to a diagnostic. - */ -export type Severity = "hint" | "information" | "warning" | "error" | "fatal"; -export type DiagnosticTags = DiagnosticTag[]; -/** - * Serializable representation of a [Diagnostic](super::Diagnostic) advice - -See the [Visitor] trait for additional documentation on all the supported advice types. - */ -export type Advice = - | { log: [LogCategory, MarkupBuf] } - | { list: MarkupBuf[] } - | { frame: Location } - | { diff: TextEdit } - | { backtrace: [MarkupBuf, Backtrace] } - | { command: string } - | { group: [MarkupBuf, Advices] }; -/** - * Represents the resource a diagnostic is associated with. - */ -export type Resource_for_String = "argv" | "memory" | { file: string }; -export type TextRange = [TextSize, TextSize]; -export interface MarkupNodeBuf { - content: string; - elements: MarkupElement[]; -} -/** - * Internal enum used to automatically generate bit offsets for [DiagnosticTags] and help with the implementation of `serde` and `schemars` for tags. - */ -export type DiagnosticTag = - | "fixable" - | "internal" - | "unnecessaryCode" - | "deprecatedCode" - | "verbose"; -/** - * The category for a log advice, defines how the message should be presented to the user. - */ -export type LogCategory = "none" | "info" | "warn" | "error"; -export interface TextEdit { - dictionary: string; - ops: CompressedOp[]; -} -export type Backtrace = BacktraceFrame[]; -export type TextSize = number; -/** - * Enumeration of all the supported markup elements - */ -export type MarkupElement = - | "Emphasis" - | "Dim" - | "Italic" - | "Underline" - | "Error" - | "Success" - | "Warn" - | "Info" - | "Debug" - | "Trace" - | "Inverse" - | { Hyperlink: { href: string } }; -export type CompressedOp = - | { diffOp: DiffOp } - | { equalLines: { line_count: number } }; -/** - * Serializable representation of a backtrace frame. - */ -export interface BacktraceFrame { - ip: number; - symbols: BacktraceSymbol[]; -} -export type DiffOp = - | { equal: { range: TextRange } } - | { insert: { range: TextRange } } - | { delete: { range: TextRange } }; -/** - * Serializable representation of a backtrace frame symbol. - */ -export interface BacktraceSymbol { - colno?: number; - filename?: string; - lineno?: number; - name?: string; -} -export interface GetCompletionsParams { - /** - * The File for which a completion is requested. - */ - path: PgLTPath; - /** - * The Cursor position in the file for which a completion is requested. - */ - position: TextSize; -} -export interface CompletionResult { - items: CompletionItem[]; -} -export interface CompletionItem { - description: string; - kind: CompletionItemKind; - label: string; - preselected: boolean; - score: number; -} -export type CompletionItemKind = "table" | "function" | "column"; -export interface UpdateSettingsParams { - configuration: PartialConfiguration; - gitignore_matches: string[]; - skip_db: boolean; - vcs_base_path?: string; - workspace_directory?: string; -} -/** - * The configuration that is contained inside the configuration file. - */ -export interface PartialConfiguration { - /** - * A field for the [JSON schema](https://json-schema.org/) specification - */ - $schema?: string; - /** - * The configuration of the database connection - */ - db?: PartialDatabaseConfiguration; - /** - * The configuration of the filesystem - */ - files?: PartialFilesConfiguration; - /** - * The configuration for the linter - */ - linter?: PartialLinterConfiguration; - /** - * Configure migrations - */ - migrations?: PartialMigrationsConfiguration; - /** - * The configuration of the VCS integration - */ - vcs?: PartialVcsConfiguration; -} -/** - * The configuration of the database connection. - */ -export interface PartialDatabaseConfiguration { - /** - * The connection timeout in seconds. - */ - connTimeoutSecs?: number; - /** - * The name of the database. - */ - database?: string; - /** - * The host of the database. - */ - host?: string; - /** - * The password to connect to the database. - */ - password?: string; - /** - * The port of the database. - */ - port?: number; - /** - * The username to connect to the database. - */ - username?: string; -} -/** - * The configuration of the filesystem - */ -export interface PartialFilesConfiguration { - /** - * A list of Unix shell style patterns. Will ignore files/folders that will match these patterns. - */ - ignore?: StringSet; - /** - * A list of Unix shell style patterns. Will handle only those files/folders that will match these patterns. - */ - include?: StringSet; - /** - * The maximum allowed size for source code files in bytes. Files above this limit will be ignored for performance reasons. Defaults to 1 MiB - */ - maxSize?: number; -} -export interface PartialLinterConfiguration { - /** - * if `false`, it disables the feature and the linter won't be executed. `true` by default - */ - enabled?: boolean; - /** - * A list of Unix shell style patterns. The formatter will ignore files/folders that will match these patterns. - */ - ignore?: StringSet; - /** - * A list of Unix shell style patterns. The formatter will include files/folders that will match these patterns. - */ - include?: StringSet; - /** - * List of rules - */ - rules?: Rules; -} -/** - * The configuration of the filesystem - */ -export interface PartialMigrationsConfiguration { - /** - * Ignore any migrations before this timestamp - */ - after?: number; - /** - * The directory where the migration files are stored - */ - migrationsDir?: string; -} -/** - * Set of properties to integrate with a VCS software. - */ -export interface PartialVcsConfiguration { - /** - * The kind of client. - */ - clientKind?: VcsClientKind; - /** - * The main branch of the project - */ - defaultBranch?: string; - /** - * Whether we should integrate itself with the VCS client - */ - enabled?: boolean; - /** - * The folder where we should check for VCS files. By default, we will use the same folder where `pglt.jsonc` was found. - -If we can't find the configuration, it will attempt to use the current working directory. If no current working directory can't be found, we won't use the VCS integration, and a diagnostic will be emitted - */ - root?: string; - /** - * Whether we should use the VCS ignore file. When [true], we will ignore the files specified in the ignore file. - */ - useIgnoreFile?: boolean; -} -export type StringSet = string[]; -export interface Rules { - /** - * It enables ALL rules. The rules that belong to `nursery` won't be enabled. - */ - all?: boolean; - /** - * It enables the lint rules recommended by PgLT. `true` by default. - */ - recommended?: boolean; - safety?: Safety; -} -export type VcsClientKind = "git"; -/** - * A list of rules that belong to this group - */ -export interface Safety { - /** - * Adding a new column that is NOT NULL and has no default value to an existing table effectively makes it required. - */ - addingRequiredField?: RuleConfiguration_for_Null; - /** - * It enables ALL rules for this group. - */ - all?: boolean; - /** - * Dropping a column may break existing clients. - */ - banDropColumn?: RuleConfiguration_for_Null; - /** - * Dropping a NOT NULL constraint may break existing clients. - */ - banDropNotNull?: RuleConfiguration_for_Null; - /** - * Dropping a table may break existing clients. - */ - banDropTable?: RuleConfiguration_for_Null; - /** - * It enables the recommended rules for this group - */ - recommended?: boolean; -} -export type RuleConfiguration_for_Null = - | RulePlainConfiguration - | RuleWithOptions_for_Null; -export type RulePlainConfiguration = "warn" | "error" | "info" | "off"; -export interface RuleWithOptions_for_Null { - /** - * The severity of the emitted diagnostics by the rule - */ - level: RulePlainConfiguration; - /** - * Rule's options - */ - options: null; -} -export interface OpenFileParams { - content: string; - path: PgLTPath; - version: number; -} -export interface ChangeFileParams { - changes: ChangeParams[]; - path: PgLTPath; - version: number; -} -export interface ChangeParams { - /** - * The range of the file that changed. If `None`, the whole file changed. - */ - range?: TextRange; - text: string; -} -export interface CloseFileParams { - path: PgLTPath; -} -export type Configuration = PartialConfiguration; -export interface Workspace { - isPathIgnored(params: IsPathIgnoredParams): Promise; - getFileContent(params: GetFileContentParams): Promise; - pullDiagnostics( - params: PullDiagnosticsParams, - ): Promise; - getCompletions(params: GetCompletionsParams): Promise; - updateSettings(params: UpdateSettingsParams): Promise; - openFile(params: OpenFileParams): Promise; - changeFile(params: ChangeFileParams): Promise; - closeFile(params: CloseFileParams): Promise; - destroy(): void; -} -export function createWorkspace(transport: Transport): Workspace { - return { - isPathIgnored(params) { - return transport.request("pglt/is_path_ignored", params); - }, - getFileContent(params) { - return transport.request("pglt/get_file_content", params); - }, - pullDiagnostics(params) { - return transport.request("pglt/pull_diagnostics", params); - }, - getCompletions(params) { - return transport.request("pglt/get_completions", params); - }, - updateSettings(params) { - return transport.request("pglt/update_settings", params); - }, - openFile(params) { - return transport.request("pglt/open_file", params); - }, - changeFile(params) { - return transport.request("pglt/change_file", params); - }, - closeFile(params) { - return transport.request("pglt/close_file", params); - }, - destroy() { - transport.destroy(); - }, - }; -} diff --git a/packages/@pglt/backend-jsonrpc/tests/workspace.test.mjs b/packages/@pglt/backend-jsonrpc/tests/workspace.test.mjs deleted file mode 100644 index fc6c71c83..000000000 --- a/packages/@pglt/backend-jsonrpc/tests/workspace.test.mjs +++ /dev/null @@ -1,54 +0,0 @@ -import { resolve } from "node:path"; -import { fileURLToPath } from "node:url"; -import { describe, expect, it } from "vitest"; - -import { createWorkspaceWithBinary } from "../dist"; - -describe("Workspace API", () => { - it("should process remote requests", async () => { - const extension = process.platform === "win32" ? ".exe" : ""; - const command = resolve( - fileURLToPath(import.meta.url), - "../../../../..", - `target/release/pglt${extension}`, - ); - - const workspace = await createWorkspaceWithBinary(command); - await workspace.openFile({ - path: { - path: "test.sql", - was_written: false, - kind: ["Handleable"], - }, - content: "select 1 from", - version: 0, - }); - - const { diagnostics } = await workspace.pullDiagnostics({ - only: [], - skip: [], - max_diagnostics: 100, - categories: [], - path: { - path: "test.sql", - was_written: false, - kind: ["Handleable"], - }, - }); - - expect(diagnostics).toHaveLength(1); - expect(diagnostics[0].description).toBe( - "Invalid statement: syntax error at end of input", - ); - - await workspace.closeFile({ - path: { - path: "test.sql", - was_written: false, - kind: ["Handleable"], - }, - }); - - workspace.destroy(); - }); -}); diff --git a/packages/@pglt/pglt/package.json b/packages/@pglt/pglt/package.json deleted file mode 100644 index 5a5518073..000000000 --- a/packages/@pglt/pglt/package.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "pglt", - "version": "", - "bin": { - "pglt": "bin/pglt" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/supabase-community/postgres_lsp.git", - "directory": "packages/@pglt/pglt" - }, - "author": "Supabase Community", - "contributors": [ - { - "name": "Philipp Steinrötter", - "url": "https://github.com/psteinroe" - }, - { - "name": "Julian Domke", - "url": "https://github.com/juleswritescode" - } - ], - "license": "MIT or Apache-2.0", - "description": "A collection of language tools and a Language Server Protocol (LSP) implementation for Postgres, focusing on developer experience and reliable SQL tooling.", - "files": ["bin/pglt", "schema.json"], - "engines": { - "node": ">=20" - }, - "publishConfig": { - "provenance": true - }, - "optionalDependencies": { - "pglt-x86_64-windows-msvc": "", - "pglt-aarch64-windows-msvc": "", - "pglt-x86_64-apple-darwin": "", - "pglt-aarch64-apple-darwin": "", - "pglt-x86_64-linux-gnu": "", - "pglt-aarch64-linux-gnu": "" - } -} diff --git a/packages/@pglt/pglt/scripts/generate-packages.mjs b/packages/@pglt/pglt/scripts/generate-packages.mjs deleted file mode 100644 index 52c6bf8fe..000000000 --- a/packages/@pglt/pglt/scripts/generate-packages.mjs +++ /dev/null @@ -1,250 +0,0 @@ -import assert from "node:assert"; -import * as fs from "node:fs"; -import { pipeline } from "node:stream"; -import { resolve } from "node:path"; -import { fileURLToPath } from "node:url"; -import { promisify } from "node:util"; -const streamPipeline = promisify(pipeline); - -const CLI_ROOT = resolve(fileURLToPath(import.meta.url), "../.."); -const PACKAGES_PGLT_ROOT = resolve(CLI_ROOT, ".."); -const PGLT_ROOT = resolve(PACKAGES_PGLT_ROOT, "../.."); -const SUPPORTED_PLATFORMS = [ - "pc-windows-msvc", - "apple-darwin", - "unknown-linux-gnu", -]; -const SUPPORTED_ARCHITECTURES = ["x86_64", "aarch64"]; - -async function downloadSchema(releaseTag, githubToken) { - const assetUrl = `https://github.com/supabase-community/postgres_lsp/releases/download/${releaseTag}/schema.json`; - - const response = await fetch(assetUrl.trim(), { - headers: { - Authorization: `token ${githubToken}`, - Accept: "application/octet-stream", - }, - }); - - if (!response.ok) { - throw new Error(`Failed to Fetch Asset from ${assetUrl}`); - } - - // download to root. - const fileStream = fs.createWriteStream(resolve(PGLT_ROOT, "schema.json")); - - await streamPipeline(response.body, fileStream); - - console.log(`Downloaded schema for ${releaseTag}`); -} - -async function downloadBinary(platform, arch, os, releaseTag, githubToken) { - const buildName = getBuildName(platform, arch); - - const assetUrl = `https://github.com/supabase-community/postgres_lsp/releases/download/${releaseTag}/${buildName}`; - - const response = await fetch(assetUrl.trim(), { - headers: { - Authorization: `token ${githubToken}`, - Accept: "application/octet-stream", - }, - }); - - if (!response.ok) { - const error = await response.text(); - throw new Error( - `Failed to Fetch Asset from ${assetUrl} (Reason: ${error})`, - ); - } - - // just download to root. - const fileStream = fs.createWriteStream(getBinarySource(platform, arch, os)); - - await streamPipeline(response.body, fileStream); - - console.log(`Downloaded asset for ${buildName} (v${releaseTag})`); -} - -async function writeManifest(packagePath, version) { - const manifestPath = resolve(PACKAGES_PGLT_ROOT, packagePath, "package.json"); - - const manifestData = JSON.parse( - fs.readFileSync(manifestPath).toString("utf-8"), - ); - - const nativePackages = SUPPORTED_PLATFORMS.flatMap((platform) => - SUPPORTED_ARCHITECTURES.map((arch) => [ - `@pglt/${getName(platform, arch)}`, - version, - ]), - ); - - manifestData.version = version; - manifestData.optionalDependencies = Object.fromEntries(nativePackages); - - console.log(`Update manifest ${manifestPath}`); - const content = JSON.stringify(manifestData, null, 2); - - /** - * writeFileSync seemed to not work reliably? - */ - await new Promise((res, rej) => { - fs.writeFile(manifestPath, content, (e) => (e ? rej(e) : res())); - }); -} - -async function makePackageDir(platform, arch) { - const buildName = getBuildName(platform, arch); - const packageRoot = resolve(PACKAGES_PGLT_ROOT, buildName); - - await new Promise((res, rej) => { - fs.mkdir(packageRoot, {}, (e) => (e ? rej(e) : res())); - }); -} - -function copyBinaryToNativePackage(platform, arch, os) { - // Update the package.json manifest - const buildName = getBuildName(platform, arch); - const packageRoot = resolve(PACKAGES_PGLT_ROOT, buildName); - const packageName = getPackageName(platform, arch); - - const { version, license, repository, engines } = rootManifest(); - - /** - * We need to map rust triplets to NPM-known values. - * Otherwise, npm will abort the package installation. - */ - const npm_arch = arch === "aarch64" ? "arm64" : "x64"; - let libc = undefined; - let npm_os = undefined; - - switch (os) { - case "linux": { - libc = "gnu"; - npm_os = "linux"; - break; - } - case "windows": { - libc = "msvc"; - npm_os = "win32"; - break; - } - case "darwin": { - libc = undefined; - npm_os = "darwin"; - break; - } - default: { - throw new Error(`Unsupported os: ${os}`); - } - } - - const manifest = JSON.stringify( - { - name: packageName, - version, - license, - repository, - engines, - os: [npm_os], - cpu: [npm_arch], - libc, - }, - null, - 2, - ); - - const ext = getBinaryExt(os); - const manifestPath = resolve(packageRoot, "package.json"); - console.info(`Update manifest ${manifestPath}`); - fs.writeFileSync(manifestPath, manifest); - - // Copy the CLI binary - const binarySource = getBinarySource(platform, arch, os); - const binaryTarget = resolve(packageRoot, `pglt${ext}`); - - if (!fs.existsSync(binarySource)) { - console.error( - `Source for binary for ${buildName} not found at: ${binarySource}`, - ); - process.exit(1); - } - - console.info(`Copy binary ${binaryTarget}`); - fs.copyFileSync(binarySource, binaryTarget); - fs.chmodSync(binaryTarget, 0o755); -} - -function copySchemaToNativePackage(platform, arch) { - const buildName = getBuildName(platform, arch); - const packageRoot = resolve(PACKAGES_PGLT_ROOT, buildName); - - const schemaSrc = resolve(PGLT_ROOT, "schema.json"); - const schemaTarget = resolve(packageRoot, "schema.json"); - - if (!fs.existsSync(schemaSrc)) { - console.error(`schema.json not found at: ${schemaSrc}`); - process.exit(1); - } - - console.info("Copying schema.json"); - fs.copyFileSync(schemaSrc, schemaTarget); - fs.chmodSync(schemaTarget, 0o666); -} - -const rootManifest = () => - JSON.parse(fs.readFileSync(MANIFEST_PATH).toString("utf-8")); - -function getBinaryExt(os) { - return os === "windows" ? ".exe" : ""; -} - -function getBinarySource(platform, arch, os) { - const ext = getBinaryExt(os); - return resolve(PGLT_ROOT, `${getBuildName(platform, arch)}${ext}`); -} - -function getBuildName(platform, arch) { - return `pglt_${arch}-${platform}`; -} - -function getPackageName(platform, arch) { - // trim the "unknown" from linux and the "pc" from windows - const platformName = platform.split("-").slice(-2).join("-"); - return `pglt-${arch}-${platformName}`; -} - -function getOs(platform) { - return platform.split("-").find((_, idx) => idx === 1); -} - -function getVersion(releaseTag, isPrerelease) { - return releaseTag + (isPrerelease ? "-rc" : ""); -} - -(async function main() { - const githubToken = process.env.GITHUB_TOKEN; - const releaseTag = process.env.RELEASE_TAG; - assert(githubToken, "GITHUB_TOKEN not defined!"); - assert(releaseTag, "RELEASE_TAG not defined!"); - - const isPrerelease = process.env.PRERELEASE === "true"; - - await downloadSchema(releaseTag, githubToken); - const version = getVersion(releaseTag, isPrerelease); - await writeManifest("pglt", version); - await writeManifest("backend-jsonrpc", version); - - for (const platform of SUPPORTED_PLATFORMS) { - const os = getOs(platform); - - for (const arch of SUPPORTED_ARCHITECTURES) { - await makePackageDir(platform, arch); - await downloadBinary(platform, arch, os, releaseTag, githubToken); - copyBinaryToNativePackage(platform, arch, os); - copySchemaToNativePackage(platform, arch); - } - } - - process.exit(0); -})(); diff --git a/packages/@postgrestools/backend-jsonrpc/package.json b/packages/@postgrestools/backend-jsonrpc/package.json new file mode 100644 index 000000000..3d5003cb5 --- /dev/null +++ b/packages/@postgrestools/backend-jsonrpc/package.json @@ -0,0 +1,38 @@ +{ + "name": "@postgrestools/backend-jsonrpc", + "version": "", + "main": "dist/index.js", + "scripts": { + "test": "bun test", + "test:ci": "bun build && bun test", + "build": "bun build ./src/index.ts --outdir ./dist --target node" + }, + "files": [ + "dist/", + "README.md" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/supabase-community/postgres_lsp.git", + "directory": "packages/@postgrestools/backend-jsonrpc" + }, + "author": "Supabase Community", + "bugs": "ttps://github.com/supabase-community/postgres_lsp/issues", + "description": "Bindings to the JSON-RPC Workspace API of the Postgres Language Tools daemon", + "keywords": [ + "TypeScript", + "Postgres" + ], + "license": "MIT", + "publishConfig": { + "provenance": true + }, + "optionalDependencies": { + "@postgrestools/cli-win32-x64": "", + "@postgrestools/cli-win32-arm64": "", + "@postgrestools/cli-darwin-x64": "", + "@postgrestools/cli-darwin-arm64": "", + "@postgrestools/cli-linux-x64": "", + "@postgrestools/cli-linux-arm64": "" + } +} diff --git a/packages/@postgrestools/backend-jsonrpc/src/command.ts b/packages/@postgrestools/backend-jsonrpc/src/command.ts new file mode 100644 index 000000000..d25c748c8 --- /dev/null +++ b/packages/@postgrestools/backend-jsonrpc/src/command.ts @@ -0,0 +1,36 @@ +/** + * Gets the path of the binary for the current platform + * + * @returns Filesystem path to the binary, or null if no prebuilt distribution exists for the current platform + */ +export function getCommand(): string | null { + const { platform, arch } = process; + + type PlatformPaths = { + [P in NodeJS.Platform]?: { + [A in NodeJS.Architecture]?: string; + }; + }; + + const PLATFORMS: PlatformPaths = { + win32: { + x64: "@postgrestools/cli-win32-x64/postgrestools.exe", + arm64: "@postgrestools/cli-win32-arm64/postgrestools.exe", + }, + darwin: { + x64: "@postgrestools/cli-darwin-x64/postgrestools", + arm64: "@postgrestools/cli-darwin-arm64/postgrestools", + }, + linux: { + x64: "@postgrestools/cli-linux-x64/postgrestools", + arm64: "@postgrestools/cli-linux-arm64/postgrestools", + }, + }; + + const binPath = PLATFORMS?.[platform]?.[arch]; + if (!binPath) { + return null; + } + + return require.resolve(binPath); +} diff --git a/packages/@pglt/backend-jsonrpc/src/index.ts b/packages/@postgrestools/backend-jsonrpc/src/index.ts similarity index 68% rename from packages/@pglt/backend-jsonrpc/src/index.ts rename to packages/@postgrestools/backend-jsonrpc/src/index.ts index 5d4dd41b7..f16bc9ba6 100644 --- a/packages/@pglt/backend-jsonrpc/src/index.ts +++ b/packages/@postgrestools/backend-jsonrpc/src/index.ts @@ -10,12 +10,12 @@ import { type Workspace, createWorkspace as wrapTransport } from "./workspace"; * @returns A Workspace client, or null if the underlying platform is not supported */ export async function createWorkspace(): Promise { - const command = getCommand(); - if (!command) { - return null; - } + const command = getCommand(); + if (!command) { + return null; + } - return createWorkspaceWithBinary(command); + return createWorkspaceWithBinary(command); } /** @@ -27,20 +27,20 @@ export async function createWorkspace(): Promise { * @returns A Workspace client, or null if the underlying platform is not supported */ export async function createWorkspaceWithBinary( - command: string, + command: string ): Promise { - const socket = await createSocket(command); - const transport = new Transport(socket); + const socket = await createSocket(command); + const transport = new Transport(socket); - await transport.request("initialize", { - capabilities: {}, - client_info: { - name: "@pglt/backend-jsonrpc", - version: "0.0.0", - }, - }); + await transport.request("initialize", { + capabilities: {}, + client_info: { + name: "@postgrestools/backend-jsonrpc", + version: "0.0.0", + }, + }); - return wrapTransport(transport); + return wrapTransport(transport); } export * from "./workspace"; diff --git a/packages/@pglt/backend-jsonrpc/src/socket.ts b/packages/@postgrestools/backend-jsonrpc/src/socket.ts similarity index 100% rename from packages/@pglt/backend-jsonrpc/src/socket.ts rename to packages/@postgrestools/backend-jsonrpc/src/socket.ts diff --git a/packages/@pglt/backend-jsonrpc/src/transport.ts b/packages/@postgrestools/backend-jsonrpc/src/transport.ts similarity index 100% rename from packages/@pglt/backend-jsonrpc/src/transport.ts rename to packages/@postgrestools/backend-jsonrpc/src/transport.ts diff --git a/packages/@postgrestools/backend-jsonrpc/src/workspace.ts b/packages/@postgrestools/backend-jsonrpc/src/workspace.ts new file mode 100644 index 000000000..609b7aca9 --- /dev/null +++ b/packages/@postgrestools/backend-jsonrpc/src/workspace.ts @@ -0,0 +1,453 @@ +// Generated file, do not edit by hand, see `xtask/codegen` +import type { Transport } from "./transport"; +export interface IsPathIgnoredParams { + pglt_path: PgLTPath; +} +export interface PgLTPath { + /** + * Determines the kind of the file inside PostgresTools. Some files are considered as configuration files, others as manifest files, and others as files to handle + */ + kind: FileKind; + path: string; + /** + * Whether this path (usually a file) was fixed as a result of a format/lint/check command with the `--write` filag. + */ + was_written: boolean; +} +export type FileKind = FileKind2[]; +/** + * The priority of the file + */ +export type FileKind2 = "Config" | "Ignore" | "Inspectable" | "Handleable"; +export interface GetFileContentParams { + path: PgLTPath; +} +export interface PullDiagnosticsParams { + categories: RuleCategories; + max_diagnostics: number; + only: RuleCode[]; + path: PgLTPath; + skip: RuleCode[]; +} +export type RuleCategories = RuleCategory[]; +export type RuleCode = string; +export type RuleCategory = "Lint" | "Action" | "Transformation"; +export interface PullDiagnosticsResult { + diagnostics: Diagnostic[]; + errors: number; + skipped_diagnostics: number; +} +/** + * Serializable representation for a [Diagnostic](super::Diagnostic). + */ +export interface Diagnostic { + advices: Advices; + category?: Category; + description: string; + location: Location; + message: MarkupBuf; + severity: Severity; + source?: Diagnostic; + tags: DiagnosticTags; + verboseAdvices: Advices; +} +/** + * Implementation of [Visitor] collecting serializable [Advice] into a vector. + */ +export interface Advices { + advices: Advice[]; +} +export type Category = + | "lint/safety/addingRequiredField" + | "lint/safety/banDropColumn" + | "lint/safety/banDropNotNull" + | "lint/safety/banDropTable" + | "stdin" + | "check" + | "configuration" + | "database/connection" + | "internalError/io" + | "internalError/runtime" + | "internalError/fs" + | "flags/invalid" + | "project" + | "typecheck" + | "internalError/panic" + | "syntax" + | "dummy" + | "lint" + | "lint/performance" + | "lint/safety"; +export interface Location { + path?: Resource_for_String; + sourceCode?: string; + span?: TextRange; +} +export type MarkupBuf = MarkupNodeBuf[]; +/** + * The severity to associate to a diagnostic. + */ +export type Severity = "hint" | "information" | "warning" | "error" | "fatal"; +export type DiagnosticTags = DiagnosticTag[]; +/** + * Serializable representation of a [Diagnostic](super::Diagnostic) advice + +See the [Visitor] trait for additional documentation on all the supported advice types. + */ +export type Advice = + | { log: [LogCategory, MarkupBuf] } + | { list: MarkupBuf[] } + | { frame: Location } + | { diff: TextEdit } + | { backtrace: [MarkupBuf, Backtrace] } + | { command: string } + | { group: [MarkupBuf, Advices] }; +/** + * Represents the resource a diagnostic is associated with. + */ +export type Resource_for_String = "argv" | "memory" | { file: string }; +export type TextRange = [TextSize, TextSize]; +export interface MarkupNodeBuf { + content: string; + elements: MarkupElement[]; +} +/** + * Internal enum used to automatically generate bit offsets for [DiagnosticTags] and help with the implementation of `serde` and `schemars` for tags. + */ +export type DiagnosticTag = + | "fixable" + | "internal" + | "unnecessaryCode" + | "deprecatedCode" + | "verbose"; +/** + * The category for a log advice, defines how the message should be presented to the user. + */ +export type LogCategory = "none" | "info" | "warn" | "error"; +export interface TextEdit { + dictionary: string; + ops: CompressedOp[]; +} +export type Backtrace = BacktraceFrame[]; +export type TextSize = number; +/** + * Enumeration of all the supported markup elements + */ +export type MarkupElement = + | "Emphasis" + | "Dim" + | "Italic" + | "Underline" + | "Error" + | "Success" + | "Warn" + | "Info" + | "Debug" + | "Trace" + | "Inverse" + | { Hyperlink: { href: string } }; +export type CompressedOp = + | { diffOp: DiffOp } + | { equalLines: { line_count: number } }; +/** + * Serializable representation of a backtrace frame. + */ +export interface BacktraceFrame { + ip: number; + symbols: BacktraceSymbol[]; +} +export type DiffOp = + | { equal: { range: TextRange } } + | { insert: { range: TextRange } } + | { delete: { range: TextRange } }; +/** + * Serializable representation of a backtrace frame symbol. + */ +export interface BacktraceSymbol { + colno?: number; + filename?: string; + lineno?: number; + name?: string; +} +export interface GetCompletionsParams { + /** + * The File for which a completion is requested. + */ + path: PgLTPath; + /** + * The Cursor position in the file for which a completion is requested. + */ + position: TextSize; +} +export interface CompletionResult { + items: CompletionItem[]; +} +export interface CompletionItem { + description: string; + kind: CompletionItemKind; + label: string; + preselected: boolean; + score: number; +} +export type CompletionItemKind = "table" | "function" | "column"; +export interface UpdateSettingsParams { + configuration: PartialConfiguration; + gitignore_matches: string[]; + skip_db: boolean; + vcs_base_path?: string; + workspace_directory?: string; +} +/** + * The configuration that is contained inside the configuration file. + */ +export interface PartialConfiguration { + /** + * A field for the [JSON schema](https://json-schema.org/) specification + */ + $schema?: string; + /** + * The configuration of the database connection + */ + db?: PartialDatabaseConfiguration; + /** + * The configuration of the filesystem + */ + files?: PartialFilesConfiguration; + /** + * The configuration for the linter + */ + linter?: PartialLinterConfiguration; + /** + * Configure migrations + */ + migrations?: PartialMigrationsConfiguration; + /** + * The configuration of the VCS integration + */ + vcs?: PartialVcsConfiguration; +} +/** + * The configuration of the database connection. + */ +export interface PartialDatabaseConfiguration { + /** + * The connection timeout in seconds. + */ + connTimeoutSecs?: number; + /** + * The name of the database. + */ + database?: string; + /** + * The host of the database. + */ + host?: string; + /** + * The password to connect to the database. + */ + password?: string; + /** + * The port of the database. + */ + port?: number; + /** + * The username to connect to the database. + */ + username?: string; +} +/** + * The configuration of the filesystem + */ +export interface PartialFilesConfiguration { + /** + * A list of Unix shell style patterns. Will ignore files/folders that will match these patterns. + */ + ignore?: StringSet; + /** + * A list of Unix shell style patterns. Will handle only those files/folders that will match these patterns. + */ + include?: StringSet; + /** + * The maximum allowed size for source code files in bytes. Files above this limit will be ignored for performance reasons. Defaults to 1 MiB + */ + maxSize?: number; +} +export interface PartialLinterConfiguration { + /** + * if `false`, it disables the feature and the linter won't be executed. `true` by default + */ + enabled?: boolean; + /** + * A list of Unix shell style patterns. The formatter will ignore files/folders that will match these patterns. + */ + ignore?: StringSet; + /** + * A list of Unix shell style patterns. The formatter will include files/folders that will match these patterns. + */ + include?: StringSet; + /** + * List of rules + */ + rules?: Rules; +} +/** + * The configuration of the filesystem + */ +export interface PartialMigrationsConfiguration { + /** + * Ignore any migrations before this timestamp + */ + after?: number; + /** + * The directory where the migration files are stored + */ + migrationsDir?: string; +} +/** + * Set of properties to integrate with a VCS software. + */ +export interface PartialVcsConfiguration { + /** + * The kind of client. + */ + clientKind?: VcsClientKind; + /** + * The main branch of the project + */ + defaultBranch?: string; + /** + * Whether we should integrate itself with the VCS client + */ + enabled?: boolean; + /** + * The folder where we should check for VCS files. By default, we will use the same folder where `postgrestools.jsonc` was found. + +If we can't find the configuration, it will attempt to use the current working directory. If no current working directory can't be found, we won't use the VCS integration, and a diagnostic will be emitted + */ + root?: string; + /** + * Whether we should use the VCS ignore file. When [true], we will ignore the files specified in the ignore file. + */ + useIgnoreFile?: boolean; +} +export type StringSet = string[]; +export interface Rules { + /** + * It enables ALL rules. The rules that belong to `nursery` won't be enabled. + */ + all?: boolean; + /** + * It enables the lint rules recommended by PostgresTools. `true` by default. + */ + recommended?: boolean; + safety?: Safety; +} +export type VcsClientKind = "git"; +/** + * A list of rules that belong to this group + */ +export interface Safety { + /** + * Adding a new column that is NOT NULL and has no default value to an existing table effectively makes it required. + */ + addingRequiredField?: RuleConfiguration_for_Null; + /** + * It enables ALL rules for this group. + */ + all?: boolean; + /** + * Dropping a column may break existing clients. + */ + banDropColumn?: RuleConfiguration_for_Null; + /** + * Dropping a NOT NULL constraint may break existing clients. + */ + banDropNotNull?: RuleConfiguration_for_Null; + /** + * Dropping a table may break existing clients. + */ + banDropTable?: RuleConfiguration_for_Null; + /** + * It enables the recommended rules for this group + */ + recommended?: boolean; +} +export type RuleConfiguration_for_Null = + | RulePlainConfiguration + | RuleWithOptions_for_Null; +export type RulePlainConfiguration = "warn" | "error" | "info" | "off"; +export interface RuleWithOptions_for_Null { + /** + * The severity of the emitted diagnostics by the rule + */ + level: RulePlainConfiguration; + /** + * Rule's options + */ + options: null; +} +export interface OpenFileParams { + content: string; + path: PgLTPath; + version: number; +} +export interface ChangeFileParams { + changes: ChangeParams[]; + path: PgLTPath; + version: number; +} +export interface ChangeParams { + /** + * The range of the file that changed. If `None`, the whole file changed. + */ + range?: TextRange; + text: string; +} +export interface CloseFileParams { + path: PgLTPath; +} +export type Configuration = PartialConfiguration; +export interface Workspace { + isPathIgnored(params: IsPathIgnoredParams): Promise; + getFileContent(params: GetFileContentParams): Promise; + pullDiagnostics( + params: PullDiagnosticsParams + ): Promise; + getCompletions(params: GetCompletionsParams): Promise; + updateSettings(params: UpdateSettingsParams): Promise; + openFile(params: OpenFileParams): Promise; + changeFile(params: ChangeFileParams): Promise; + closeFile(params: CloseFileParams): Promise; + destroy(): void; +} +export function createWorkspace(transport: Transport): Workspace { + return { + isPathIgnored(params) { + return transport.request("pglt/is_path_ignored", params); + }, + getFileContent(params) { + return transport.request("pglt/get_file_content", params); + }, + pullDiagnostics(params) { + return transport.request("pglt/pull_diagnostics", params); + }, + getCompletions(params) { + return transport.request("pglt/get_completions", params); + }, + updateSettings(params) { + return transport.request("pglt/update_settings", params); + }, + openFile(params) { + return transport.request("pglt/open_file", params); + }, + changeFile(params) { + return transport.request("pglt/change_file", params); + }, + closeFile(params) { + return transport.request("pglt/close_file", params); + }, + destroy() { + transport.destroy(); + }, + }; +} diff --git a/packages/@pglt/backend-jsonrpc/tests/transport.test.mjs b/packages/@postgrestools/backend-jsonrpc/tests/transport.test.mjs similarity index 100% rename from packages/@pglt/backend-jsonrpc/tests/transport.test.mjs rename to packages/@postgrestools/backend-jsonrpc/tests/transport.test.mjs diff --git a/packages/@postgrestools/backend-jsonrpc/tests/workspace.test.mjs b/packages/@postgrestools/backend-jsonrpc/tests/workspace.test.mjs new file mode 100644 index 000000000..efab4f56d --- /dev/null +++ b/packages/@postgrestools/backend-jsonrpc/tests/workspace.test.mjs @@ -0,0 +1,54 @@ +import { resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { describe, expect, it } from "vitest"; + +import { createWorkspaceWithBinary } from "../dist"; + +describe("Workspace API", () => { + it("should process remote requests", async () => { + const extension = process.platform === "win32" ? ".exe" : ""; + const command = resolve( + fileURLToPath(import.meta.url), + "../../../../..", + `target/release/postgrestools${extension}` + ); + + const workspace = await createWorkspaceWithBinary(command); + await workspace.openFile({ + path: { + path: "test.sql", + was_written: false, + kind: ["Handleable"], + }, + content: "select 1 from", + version: 0, + }); + + const { diagnostics } = await workspace.pullDiagnostics({ + only: [], + skip: [], + max_diagnostics: 100, + categories: [], + path: { + path: "test.sql", + was_written: false, + kind: ["Handleable"], + }, + }); + + expect(diagnostics).toHaveLength(1); + expect(diagnostics[0].description).toBe( + "Invalid statement: syntax error at end of input" + ); + + await workspace.closeFile({ + path: { + path: "test.sql", + was_written: false, + kind: ["Handleable"], + }, + }); + + workspace.destroy(); + }); +}); diff --git a/packages/@pglt/pglt/bin/pglt b/packages/@postgrestools/postgrestools/bin/pglt similarity index 50% rename from packages/@pglt/pglt/bin/pglt rename to packages/@postgrestools/postgrestools/bin/pglt index 4f0101617..47d78bb65 100755 --- a/packages/@pglt/pglt/bin/pglt +++ b/packages/@postgrestools/postgrestools/bin/pglt @@ -7,20 +7,20 @@ const { platform, arch, env } = process; */ const PLATFORMS = { win32: { - x64: "pglt-x86_64-windows-msvc/pglt.exe", - arm64: "pglt-aarch64-windows-msvc/pglt.exe", + x64: "postgrestools-x86_64-windows-msvc/postgrestools.exe", + arm64: "postgrestools-aarch64-windows-msvc/postgrestools.exe", }, darwin: { - x64: "pglt-x86_64-apple-darwin/pglt", - arm64: "pglt-aarch64-apple-darwin/pglt", + x64: "postgrestools-x86_64-apple-darwin/postgrestools", + arm64: "postgrestools-aarch64-apple-darwin/postgrestools", }, linux: { - x64: "pglt-x86_64-linux-gnu/pglt", - arm64: "pglt-aarch64-linux-gnu/pglt", + x64: "postgrestools-x86_64-linux-gnu/postgrestools", + arm64: "postgrestools-aarch64-linux-gnu/postgrestools", }, }; -const binPath = env.PGLT_BINARY || PLATFORMS?.[platform]?.[arch]; +const binPath = env.POSTGRESTOOLS_BINARY || PLATFORMS?.[platform]?.[arch]; if (binPath) { const result = require("child_process").spawnSync( @@ -40,7 +40,7 @@ if (binPath) { process.exitCode = result.status; } else { console.error( - "The pglt CLI package doesn't ship with prebuilt binaries for your platform yet. Please file an issue in the main repository." + "The PostgresTools CLI package doesn't ship with prebuilt binaries for your platform yet. Please file an issue in the main repository." ); process.exitCode = 1; } diff --git a/packages/@postgrestools/postgrestools/package.json b/packages/@postgrestools/postgrestools/package.json new file mode 100644 index 000000000..42f786d15 --- /dev/null +++ b/packages/@postgrestools/postgrestools/package.json @@ -0,0 +1,43 @@ +{ + "name": "postgrestools", + "version": "", + "bin": { + "postgrestools": "bin/postgrestools" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/supabase-community/postgres_lsp.git", + "directory": "packages/@postgrestools/postgrestools" + }, + "author": "Supabase Community", + "contributors": [ + { + "name": "Philipp Steinrötter", + "url": "https://github.com/psteinroe" + }, + { + "name": "Julian Domke", + "url": "https://github.com/juleswritescode" + } + ], + "license": "MIT or Apache-2.0", + "description": "A collection of language tools and a Language Server Protocol (LSP) implementation for Postgres, focusing on developer experience and reliable SQL tooling.", + "files": [ + "bin/postgrestools", + "schema.json" + ], + "engines": { + "node": ">=20" + }, + "publishConfig": { + "provenance": true + }, + "optionalDependencies": { + "postgrestools-x86_64-windows-msvc": "", + "postgrestools-aarch64-windows-msvc": "", + "postgrestools-x86_64-apple-darwin": "", + "postgrestools-aarch64-apple-darwin": "", + "postgrestools-x86_64-linux-gnu": "", + "postgrestools-aarch64-linux-gnu": "" + } +} diff --git a/packages/@postgrestools/postgrestools/scripts/generate-packages.mjs b/packages/@postgrestools/postgrestools/scripts/generate-packages.mjs new file mode 100644 index 000000000..0be0138e4 --- /dev/null +++ b/packages/@postgrestools/postgrestools/scripts/generate-packages.mjs @@ -0,0 +1,256 @@ +import assert from "node:assert"; +import * as fs from "node:fs"; +import { pipeline } from "node:stream"; +import { resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; +const streamPipeline = promisify(pipeline); + +const CLI_ROOT = resolve(fileURLToPath(import.meta.url), "../.."); +const PACKAGES_POSTGRESTOOLS_ROOT = resolve(CLI_ROOT, ".."); +const POSTGRESTOOLS_ROOT = resolve(PACKAGES_POSTGRESTOOLS_ROOT, "../.."); +const SUPPORTED_PLATFORMS = [ + "pc-windows-msvc", + "apple-darwin", + "unknown-linux-gnu", +]; +const SUPPORTED_ARCHITECTURES = ["x86_64", "aarch64"]; + +async function downloadSchema(releaseTag, githubToken) { + const assetUrl = `https://github.com/supabase-community/postgres_lsp/releases/download/${releaseTag}/schema.json`; + + const response = await fetch(assetUrl.trim(), { + headers: { + Authorization: `token ${githubToken}`, + Accept: "application/octet-stream", + }, + }); + + if (!response.ok) { + throw new Error(`Failed to Fetch Asset from ${assetUrl}`); + } + + // download to root. + const fileStream = fs.createWriteStream( + resolve(POSTGRESTOOLS_ROOT, "schema.json") + ); + + await streamPipeline(response.body, fileStream); + + console.log(`Downloaded schema for ${releaseTag}`); +} + +async function downloadBinary(platform, arch, os, releaseTag, githubToken) { + const buildName = getBuildName(platform, arch); + + const assetUrl = `https://github.com/supabase-community/postgres_lsp/releases/download/${releaseTag}/${buildName}`; + + const response = await fetch(assetUrl.trim(), { + headers: { + Authorization: `token ${githubToken}`, + Accept: "application/octet-stream", + }, + }); + + if (!response.ok) { + const error = await response.text(); + throw new Error( + `Failed to Fetch Asset from ${assetUrl} (Reason: ${error})` + ); + } + + // just download to root. + const fileStream = fs.createWriteStream(getBinarySource(platform, arch, os)); + + await streamPipeline(response.body, fileStream); + + console.log(`Downloaded asset for ${buildName} (v${releaseTag})`); +} + +async function writeManifest(packagePath, version) { + const manifestPath = resolve( + PACKAGES_POSTGRESTOOLS_ROOT, + packagePath, + "package.json" + ); + + const manifestData = JSON.parse( + fs.readFileSync(manifestPath).toString("utf-8") + ); + + const nativePackages = SUPPORTED_PLATFORMS.flatMap((platform) => + SUPPORTED_ARCHITECTURES.map((arch) => [ + `@postgrestools/${getName(platform, arch)}`, + version, + ]) + ); + + manifestData.version = version; + manifestData.optionalDependencies = Object.fromEntries(nativePackages); + + console.log(`Update manifest ${manifestPath}`); + const content = JSON.stringify(manifestData, null, 2); + + /** + * writeFileSync seemed to not work reliably? + */ + await new Promise((res, rej) => { + fs.writeFile(manifestPath, content, (e) => (e ? rej(e) : res())); + }); +} + +async function makePackageDir(platform, arch) { + const buildName = getBuildName(platform, arch); + const packageRoot = resolve(PACKAGES_POSTGRESTOOLS_ROOT, buildName); + + await new Promise((res, rej) => { + fs.mkdir(packageRoot, {}, (e) => (e ? rej(e) : res())); + }); +} + +function copyBinaryToNativePackage(platform, arch, os) { + // Update the package.json manifest + const buildName = getBuildName(platform, arch); + const packageRoot = resolve(PACKAGES_POSTGRESTOOLS_ROOT, buildName); + const packageName = getPackageName(platform, arch); + + const { version, license, repository, engines } = rootManifest(); + + /** + * We need to map rust triplets to NPM-known values. + * Otherwise, npm will abort the package installation. + */ + const npm_arch = arch === "aarch64" ? "arm64" : "x64"; + let libc = undefined; + let npm_os = undefined; + + switch (os) { + case "linux": { + libc = "gnu"; + npm_os = "linux"; + break; + } + case "windows": { + libc = "msvc"; + npm_os = "win32"; + break; + } + case "darwin": { + libc = undefined; + npm_os = "darwin"; + break; + } + default: { + throw new Error(`Unsupported os: ${os}`); + } + } + + const manifest = JSON.stringify( + { + name: packageName, + version, + license, + repository, + engines, + os: [npm_os], + cpu: [npm_arch], + libc, + }, + null, + 2 + ); + + const ext = getBinaryExt(os); + const manifestPath = resolve(packageRoot, "package.json"); + console.info(`Update manifest ${manifestPath}`); + fs.writeFileSync(manifestPath, manifest); + + // Copy the CLI binary + const binarySource = getBinarySource(platform, arch, os); + const binaryTarget = resolve(packageRoot, `postgrestools${ext}`); + + if (!fs.existsSync(binarySource)) { + console.error( + `Source for binary for ${buildName} not found at: ${binarySource}` + ); + process.exit(1); + } + + console.info(`Copy binary ${binaryTarget}`); + fs.copyFileSync(binarySource, binaryTarget); + fs.chmodSync(binaryTarget, 0o755); +} + +function copySchemaToNativePackage(platform, arch) { + const buildName = getBuildName(platform, arch); + const packageRoot = resolve(PACKAGES_POSTGRESTOOLS_ROOT, buildName); + + const schemaSrc = resolve(POSTGRESTOOLS_ROOT, "schema.json"); + const schemaTarget = resolve(packageRoot, "schema.json"); + + if (!fs.existsSync(schemaSrc)) { + console.error(`schema.json not found at: ${schemaSrc}`); + process.exit(1); + } + + console.info("Copying schema.json"); + fs.copyFileSync(schemaSrc, schemaTarget); + fs.chmodSync(schemaTarget, 0o666); +} + +const rootManifest = () => + JSON.parse(fs.readFileSync(MANIFEST_PATH).toString("utf-8")); + +function getBinaryExt(os) { + return os === "windows" ? ".exe" : ""; +} + +function getBinarySource(platform, arch, os) { + const ext = getBinaryExt(os); + return resolve(POSTGRESTOOLS_ROOT, `${getBuildName(platform, arch)}${ext}`); +} + +function getBuildName(platform, arch) { + return `pglt_${arch}-${platform}`; +} + +function getPackageName(platform, arch) { + // trim the "unknown" from linux and the "pc" from windows + const platformName = platform.split("-").slice(-2).join("-"); + return `postgrestools-${arch}-${platformName}`; +} + +function getOs(platform) { + return platform.split("-").find((_, idx) => idx === 1); +} + +function getVersion(releaseTag, isPrerelease) { + return releaseTag + (isPrerelease ? "-rc" : ""); +} + +(async function main() { + const githubToken = process.env.GITHUB_TOKEN; + const releaseTag = process.env.RELEASE_TAG; + assert(githubToken, "GITHUB_TOKEN not defined!"); + assert(releaseTag, "RELEASE_TAG not defined!"); + + const isPrerelease = process.env.PRERELEASE === "true"; + + await downloadSchema(releaseTag, githubToken); + const version = getVersion(releaseTag, isPrerelease); + await writeManifest("postgrestools", version); + await writeManifest("backend-jsonrpc", version); + + for (const platform of SUPPORTED_PLATFORMS) { + const os = getOs(platform); + + for (const arch of SUPPORTED_ARCHITECTURES) { + await makePackageDir(platform, arch); + await downloadBinary(platform, arch, os, releaseTag, githubToken); + copyBinaryToNativePackage(platform, arch, os); + copySchemaToNativePackage(platform, arch); + } + } + + process.exit(0); +})(); From f980349a447b96ada760694d8065c3d976184fc0 Mon Sep 17 00:00:00 2001 From: Julian Date: Tue, 18 Mar 2025 08:41:26 +0100 Subject: [PATCH 2/3] rename methods, run formatter --- bun.lock | 40 +- package.json | 33 +- .../backend-jsonrpc/package.json | 66 +- .../backend-jsonrpc/src/command.ts | 50 +- .../backend-jsonrpc/src/index.ts | 32 +- .../backend-jsonrpc/src/workspace.ts | 614 +++++++++--------- .../backend-jsonrpc/tests/workspace.test.mjs | 82 +-- .../@postgrestools/postgrestools/package.json | 79 ++- .../scripts/generate-packages.mjs | 372 +++++------ 9 files changed, 680 insertions(+), 688 deletions(-) diff --git a/bun.lock b/bun.lock index 1dea8b420..777f94c77 100644 --- a/bun.lock +++ b/bun.lock @@ -11,31 +11,29 @@ "typescript": "^5", }, }, - "packages/@pglt/backend-jsonrpc": { - "name": "@pglt/backend-jsonrpc", + "packages/@postgrestools/backend-jsonrpc": { + "name": "@postgrestools/backend-jsonrpc", "optionalDependencies": { - "@pglt/cli-darwin-arm64": "", - "@pglt/cli-darwin-x64": "", - "@pglt/cli-linux-arm64": "", - "@pglt/cli-linux-arm64-musl": "", - "@pglt/cli-linux-x64": "", - "@pglt/cli-linux-x64-musl": "", - "@pglt/cli-win32-arm64": "", - "@pglt/cli-win32-x64": "", + "@postgrestools/cli-darwin-arm64": "", + "@postgrestools/cli-darwin-x64": "", + "@postgrestools/cli-linux-arm64": "", + "@postgrestools/cli-linux-x64": "", + "@postgrestools/cli-win32-arm64": "", + "@postgrestools/cli-win32-x64": "", }, }, - "packages/@pglt/pglt": { - "name": "pglt", + "packages/@postgrestools/postgrestools": { + "name": "postgrestools", "bin": { - "pglt": "bin/pglt", + "postgrestools": "bin/postgrestools", }, "optionalDependencies": { - "pglt-aarch64-apple-darwin": "", - "pglt-aarch64-linux-gnu": "", - "pglt-aarch64-windows-msvc": "", - "pglt-x86_64-apple-darwin": "", - "pglt-x86_64-linux-gnu": "", - "pglt-x86_64-windows-msvc": "", + "postgrestools-aarch64-apple-darwin": "", + "postgrestools-aarch64-linux-gnu": "", + "postgrestools-aarch64-windows-msvc": "", + "postgrestools-x86_64-apple-darwin": "", + "postgrestools-x86_64-linux-gnu": "", + "postgrestools-x86_64-windows-msvc": "", }, }, }, @@ -58,7 +56,7 @@ "@biomejs/cli-win32-x64": ["@biomejs/cli-win32-x64@1.9.4", "", { "os": "win32", "cpu": "x64" }, "sha512-8Y5wMhVIPaWe6jw2H+KlEm4wP/f7EW3810ZLmDlrEEy5KvBsb9ECEfu/kMWD484ijfQ8+nIi0giMgu9g1UAuuA=="], - "@pglt/backend-jsonrpc": ["@pglt/backend-jsonrpc@workspace:packages/@pglt/backend-jsonrpc"], + "@postgrestools/backend-jsonrpc": ["@postgrestools/backend-jsonrpc@workspace:packages/@postgrestools/backend-jsonrpc"], "@types/bun": ["@types/bun@1.2.5", "", { "dependencies": { "bun-types": "1.2.5" } }, "sha512-w2OZTzrZTVtbnJew1pdFmgV99H0/L+Pvw+z1P67HaR18MHOzYnTYOi6qzErhK8HyT+DB782ADVPPE92Xu2/Opg=="], @@ -68,7 +66,7 @@ "bun-types": ["bun-types@1.2.5", "", { "dependencies": { "@types/node": "*", "@types/ws": "~8.5.10" } }, "sha512-3oO6LVGGRRKI4kHINx5PIdIgnLRb7l/SprhzqXapmoYkFl5m4j6EvALvbDVuuBFaamB46Ap6HCUxIXNLCGy+tg=="], - "pglt": ["pglt@workspace:packages/@pglt/pglt"], + "postgrestools": ["postgrestools@workspace:packages/@postgrestools/postgrestools"], "typescript": ["typescript@5.8.2", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-aJn6wq13/afZp/jT9QZmwEjDqqvSGp1VT5GVg+f/t6/oVyrgXM6BY1h9BRh/O5p3PlUPAe+WuiEZOmb/49RqoQ=="], diff --git a/package.json b/package.json index 82b06731e..bf9303007 100644 --- a/package.json +++ b/package.json @@ -1,17 +1,20 @@ { - "name": "@pglt/monorepo", - "version": "0.0.0", - "private": true, - "devDependencies": { - "@biomejs/biome": "1.9.4", - "@types/bun": "latest" - }, - "peerDependencies": { - "typescript": "^5" - }, - "workspaces": ["packages/@pglt/pglt", "packages/@pglt/backend-jsonrpc"], - "keywords": [], - "author": "Supabase Community", - "license": "MIT OR Apache-2.0", - "packageManager": "bun@1" + "name": "@postgrestools/monorepo", + "version": "0.0.0", + "private": true, + "devDependencies": { + "@biomejs/biome": "1.9.4", + "@types/bun": "latest" + }, + "peerDependencies": { + "typescript": "^5" + }, + "workspaces": [ + "packages/@postgrestools/postgrestools", + "packages/@postgrestools/backend-jsonrpc" + ], + "keywords": [], + "author": "Supabase Community", + "license": "MIT OR Apache-2.0", + "packageManager": "bun@1" } diff --git a/packages/@postgrestools/backend-jsonrpc/package.json b/packages/@postgrestools/backend-jsonrpc/package.json index 3d5003cb5..fd5357d1e 100644 --- a/packages/@postgrestools/backend-jsonrpc/package.json +++ b/packages/@postgrestools/backend-jsonrpc/package.json @@ -1,38 +1,32 @@ { - "name": "@postgrestools/backend-jsonrpc", - "version": "", - "main": "dist/index.js", - "scripts": { - "test": "bun test", - "test:ci": "bun build && bun test", - "build": "bun build ./src/index.ts --outdir ./dist --target node" - }, - "files": [ - "dist/", - "README.md" - ], - "repository": { - "type": "git", - "url": "git+https://github.com/supabase-community/postgres_lsp.git", - "directory": "packages/@postgrestools/backend-jsonrpc" - }, - "author": "Supabase Community", - "bugs": "ttps://github.com/supabase-community/postgres_lsp/issues", - "description": "Bindings to the JSON-RPC Workspace API of the Postgres Language Tools daemon", - "keywords": [ - "TypeScript", - "Postgres" - ], - "license": "MIT", - "publishConfig": { - "provenance": true - }, - "optionalDependencies": { - "@postgrestools/cli-win32-x64": "", - "@postgrestools/cli-win32-arm64": "", - "@postgrestools/cli-darwin-x64": "", - "@postgrestools/cli-darwin-arm64": "", - "@postgrestools/cli-linux-x64": "", - "@postgrestools/cli-linux-arm64": "" - } + "name": "@postgrestools/backend-jsonrpc", + "version": "", + "main": "dist/index.js", + "scripts": { + "test": "bun test", + "test:ci": "bun build && bun test", + "build": "bun build ./src/index.ts --outdir ./dist --target node" + }, + "files": ["dist/", "README.md"], + "repository": { + "type": "git", + "url": "git+https://github.com/supabase-community/postgres_lsp.git", + "directory": "packages/@postgrestools/backend-jsonrpc" + }, + "author": "Supabase Community", + "bugs": "ttps://github.com/supabase-community/postgres_lsp/issues", + "description": "Bindings to the JSON-RPC Workspace API of the Postgres Language Tools daemon", + "keywords": ["TypeScript", "Postgres"], + "license": "MIT", + "publishConfig": { + "provenance": true + }, + "optionalDependencies": { + "@postgrestools/cli-win32-x64": "", + "@postgrestools/cli-win32-arm64": "", + "@postgrestools/cli-darwin-x64": "", + "@postgrestools/cli-darwin-arm64": "", + "@postgrestools/cli-linux-x64": "", + "@postgrestools/cli-linux-arm64": "" + } } diff --git a/packages/@postgrestools/backend-jsonrpc/src/command.ts b/packages/@postgrestools/backend-jsonrpc/src/command.ts index d25c748c8..1f3ef398f 100644 --- a/packages/@postgrestools/backend-jsonrpc/src/command.ts +++ b/packages/@postgrestools/backend-jsonrpc/src/command.ts @@ -4,33 +4,33 @@ * @returns Filesystem path to the binary, or null if no prebuilt distribution exists for the current platform */ export function getCommand(): string | null { - const { platform, arch } = process; + const { platform, arch } = process; - type PlatformPaths = { - [P in NodeJS.Platform]?: { - [A in NodeJS.Architecture]?: string; - }; - }; + type PlatformPaths = { + [P in NodeJS.Platform]?: { + [A in NodeJS.Architecture]?: string; + }; + }; - const PLATFORMS: PlatformPaths = { - win32: { - x64: "@postgrestools/cli-win32-x64/postgrestools.exe", - arm64: "@postgrestools/cli-win32-arm64/postgrestools.exe", - }, - darwin: { - x64: "@postgrestools/cli-darwin-x64/postgrestools", - arm64: "@postgrestools/cli-darwin-arm64/postgrestools", - }, - linux: { - x64: "@postgrestools/cli-linux-x64/postgrestools", - arm64: "@postgrestools/cli-linux-arm64/postgrestools", - }, - }; + const PLATFORMS: PlatformPaths = { + win32: { + x64: "@postgrestools/cli-win32-x64/postgrestools.exe", + arm64: "@postgrestools/cli-win32-arm64/postgrestools.exe", + }, + darwin: { + x64: "@postgrestools/cli-darwin-x64/postgrestools", + arm64: "@postgrestools/cli-darwin-arm64/postgrestools", + }, + linux: { + x64: "@postgrestools/cli-linux-x64/postgrestools", + arm64: "@postgrestools/cli-linux-arm64/postgrestools", + }, + }; - const binPath = PLATFORMS?.[platform]?.[arch]; - if (!binPath) { - return null; - } + const binPath = PLATFORMS?.[platform]?.[arch]; + if (!binPath) { + return null; + } - return require.resolve(binPath); + return require.resolve(binPath); } diff --git a/packages/@postgrestools/backend-jsonrpc/src/index.ts b/packages/@postgrestools/backend-jsonrpc/src/index.ts index f16bc9ba6..92ed6660e 100644 --- a/packages/@postgrestools/backend-jsonrpc/src/index.ts +++ b/packages/@postgrestools/backend-jsonrpc/src/index.ts @@ -10,12 +10,12 @@ import { type Workspace, createWorkspace as wrapTransport } from "./workspace"; * @returns A Workspace client, or null if the underlying platform is not supported */ export async function createWorkspace(): Promise { - const command = getCommand(); - if (!command) { - return null; - } + const command = getCommand(); + if (!command) { + return null; + } - return createWorkspaceWithBinary(command); + return createWorkspaceWithBinary(command); } /** @@ -27,20 +27,20 @@ export async function createWorkspace(): Promise { * @returns A Workspace client, or null if the underlying platform is not supported */ export async function createWorkspaceWithBinary( - command: string + command: string, ): Promise { - const socket = await createSocket(command); - const transport = new Transport(socket); + const socket = await createSocket(command); + const transport = new Transport(socket); - await transport.request("initialize", { - capabilities: {}, - client_info: { - name: "@postgrestools/backend-jsonrpc", - version: "0.0.0", - }, - }); + await transport.request("initialize", { + capabilities: {}, + client_info: { + name: "@postgrestools/backend-jsonrpc", + version: "0.0.0", + }, + }); - return wrapTransport(transport); + return wrapTransport(transport); } export * from "./workspace"; diff --git a/packages/@postgrestools/backend-jsonrpc/src/workspace.ts b/packages/@postgrestools/backend-jsonrpc/src/workspace.ts index 609b7aca9..e71d94575 100644 --- a/packages/@postgrestools/backend-jsonrpc/src/workspace.ts +++ b/packages/@postgrestools/backend-jsonrpc/src/workspace.ts @@ -1,18 +1,18 @@ // Generated file, do not edit by hand, see `xtask/codegen` import type { Transport } from "./transport"; export interface IsPathIgnoredParams { - pglt_path: PgLTPath; + pglt_path: PgLTPath; } export interface PgLTPath { - /** - * Determines the kind of the file inside PostgresTools. Some files are considered as configuration files, others as manifest files, and others as files to handle - */ - kind: FileKind; - path: string; - /** - * Whether this path (usually a file) was fixed as a result of a format/lint/check command with the `--write` filag. - */ - was_written: boolean; + /** + * Determines the kind of the file inside PostgresTools. Some files are considered as configuration files, others as manifest files, and others as files to handle + */ + kind: FileKind; + path: string; + /** + * Whether this path (usually a file) was fixed as a result of a format/lint/check command with the `--write` filag. + */ + was_written: boolean; } export type FileKind = FileKind2[]; /** @@ -20,68 +20,68 @@ export type FileKind = FileKind2[]; */ export type FileKind2 = "Config" | "Ignore" | "Inspectable" | "Handleable"; export interface GetFileContentParams { - path: PgLTPath; + path: PgLTPath; } export interface PullDiagnosticsParams { - categories: RuleCategories; - max_diagnostics: number; - only: RuleCode[]; - path: PgLTPath; - skip: RuleCode[]; + categories: RuleCategories; + max_diagnostics: number; + only: RuleCode[]; + path: PgLTPath; + skip: RuleCode[]; } export type RuleCategories = RuleCategory[]; export type RuleCode = string; export type RuleCategory = "Lint" | "Action" | "Transformation"; export interface PullDiagnosticsResult { - diagnostics: Diagnostic[]; - errors: number; - skipped_diagnostics: number; + diagnostics: Diagnostic[]; + errors: number; + skipped_diagnostics: number; } /** * Serializable representation for a [Diagnostic](super::Diagnostic). */ export interface Diagnostic { - advices: Advices; - category?: Category; - description: string; - location: Location; - message: MarkupBuf; - severity: Severity; - source?: Diagnostic; - tags: DiagnosticTags; - verboseAdvices: Advices; + advices: Advices; + category?: Category; + description: string; + location: Location; + message: MarkupBuf; + severity: Severity; + source?: Diagnostic; + tags: DiagnosticTags; + verboseAdvices: Advices; } /** * Implementation of [Visitor] collecting serializable [Advice] into a vector. */ export interface Advices { - advices: Advice[]; + advices: Advice[]; } export type Category = - | "lint/safety/addingRequiredField" - | "lint/safety/banDropColumn" - | "lint/safety/banDropNotNull" - | "lint/safety/banDropTable" - | "stdin" - | "check" - | "configuration" - | "database/connection" - | "internalError/io" - | "internalError/runtime" - | "internalError/fs" - | "flags/invalid" - | "project" - | "typecheck" - | "internalError/panic" - | "syntax" - | "dummy" - | "lint" - | "lint/performance" - | "lint/safety"; + | "lint/safety/addingRequiredField" + | "lint/safety/banDropColumn" + | "lint/safety/banDropNotNull" + | "lint/safety/banDropTable" + | "stdin" + | "check" + | "configuration" + | "database/connection" + | "internalError/io" + | "internalError/runtime" + | "internalError/fs" + | "flags/invalid" + | "project" + | "typecheck" + | "internalError/panic" + | "syntax" + | "dummy" + | "lint" + | "lint/performance" + | "lint/safety"; export interface Location { - path?: Resource_for_String; - sourceCode?: string; - span?: TextRange; + path?: Resource_for_String; + sourceCode?: string; + span?: TextRange; } export type MarkupBuf = MarkupNodeBuf[]; /** @@ -95,38 +95,38 @@ export type DiagnosticTags = DiagnosticTag[]; See the [Visitor] trait for additional documentation on all the supported advice types. */ export type Advice = - | { log: [LogCategory, MarkupBuf] } - | { list: MarkupBuf[] } - | { frame: Location } - | { diff: TextEdit } - | { backtrace: [MarkupBuf, Backtrace] } - | { command: string } - | { group: [MarkupBuf, Advices] }; + | { log: [LogCategory, MarkupBuf] } + | { list: MarkupBuf[] } + | { frame: Location } + | { diff: TextEdit } + | { backtrace: [MarkupBuf, Backtrace] } + | { command: string } + | { group: [MarkupBuf, Advices] }; /** * Represents the resource a diagnostic is associated with. */ export type Resource_for_String = "argv" | "memory" | { file: string }; export type TextRange = [TextSize, TextSize]; export interface MarkupNodeBuf { - content: string; - elements: MarkupElement[]; + content: string; + elements: MarkupElement[]; } /** * Internal enum used to automatically generate bit offsets for [DiagnosticTags] and help with the implementation of `serde` and `schemars` for tags. */ export type DiagnosticTag = - | "fixable" - | "internal" - | "unnecessaryCode" - | "deprecatedCode" - | "verbose"; + | "fixable" + | "internal" + | "unnecessaryCode" + | "deprecatedCode" + | "verbose"; /** * The category for a log advice, defines how the message should be presented to the user. */ export type LogCategory = "none" | "info" | "warn" | "error"; export interface TextEdit { - dictionary: string; - ops: CompressedOp[]; + dictionary: string; + ops: CompressedOp[]; } export type Backtrace = BacktraceFrame[]; export type TextSize = number; @@ -134,320 +134,320 @@ export type TextSize = number; * Enumeration of all the supported markup elements */ export type MarkupElement = - | "Emphasis" - | "Dim" - | "Italic" - | "Underline" - | "Error" - | "Success" - | "Warn" - | "Info" - | "Debug" - | "Trace" - | "Inverse" - | { Hyperlink: { href: string } }; + | "Emphasis" + | "Dim" + | "Italic" + | "Underline" + | "Error" + | "Success" + | "Warn" + | "Info" + | "Debug" + | "Trace" + | "Inverse" + | { Hyperlink: { href: string } }; export type CompressedOp = - | { diffOp: DiffOp } - | { equalLines: { line_count: number } }; + | { diffOp: DiffOp } + | { equalLines: { line_count: number } }; /** * Serializable representation of a backtrace frame. */ export interface BacktraceFrame { - ip: number; - symbols: BacktraceSymbol[]; + ip: number; + symbols: BacktraceSymbol[]; } export type DiffOp = - | { equal: { range: TextRange } } - | { insert: { range: TextRange } } - | { delete: { range: TextRange } }; + | { equal: { range: TextRange } } + | { insert: { range: TextRange } } + | { delete: { range: TextRange } }; /** * Serializable representation of a backtrace frame symbol. */ export interface BacktraceSymbol { - colno?: number; - filename?: string; - lineno?: number; - name?: string; + colno?: number; + filename?: string; + lineno?: number; + name?: string; } export interface GetCompletionsParams { - /** - * The File for which a completion is requested. - */ - path: PgLTPath; - /** - * The Cursor position in the file for which a completion is requested. - */ - position: TextSize; + /** + * The File for which a completion is requested. + */ + path: PgLTPath; + /** + * The Cursor position in the file for which a completion is requested. + */ + position: TextSize; } export interface CompletionResult { - items: CompletionItem[]; + items: CompletionItem[]; } export interface CompletionItem { - description: string; - kind: CompletionItemKind; - label: string; - preselected: boolean; - score: number; + description: string; + kind: CompletionItemKind; + label: string; + preselected: boolean; + score: number; } export type CompletionItemKind = "table" | "function" | "column"; export interface UpdateSettingsParams { - configuration: PartialConfiguration; - gitignore_matches: string[]; - skip_db: boolean; - vcs_base_path?: string; - workspace_directory?: string; + configuration: PartialConfiguration; + gitignore_matches: string[]; + skip_db: boolean; + vcs_base_path?: string; + workspace_directory?: string; } /** * The configuration that is contained inside the configuration file. */ export interface PartialConfiguration { - /** - * A field for the [JSON schema](https://json-schema.org/) specification - */ - $schema?: string; - /** - * The configuration of the database connection - */ - db?: PartialDatabaseConfiguration; - /** - * The configuration of the filesystem - */ - files?: PartialFilesConfiguration; - /** - * The configuration for the linter - */ - linter?: PartialLinterConfiguration; - /** - * Configure migrations - */ - migrations?: PartialMigrationsConfiguration; - /** - * The configuration of the VCS integration - */ - vcs?: PartialVcsConfiguration; + /** + * A field for the [JSON schema](https://json-schema.org/) specification + */ + $schema?: string; + /** + * The configuration of the database connection + */ + db?: PartialDatabaseConfiguration; + /** + * The configuration of the filesystem + */ + files?: PartialFilesConfiguration; + /** + * The configuration for the linter + */ + linter?: PartialLinterConfiguration; + /** + * Configure migrations + */ + migrations?: PartialMigrationsConfiguration; + /** + * The configuration of the VCS integration + */ + vcs?: PartialVcsConfiguration; } /** * The configuration of the database connection. */ export interface PartialDatabaseConfiguration { - /** - * The connection timeout in seconds. - */ - connTimeoutSecs?: number; - /** - * The name of the database. - */ - database?: string; - /** - * The host of the database. - */ - host?: string; - /** - * The password to connect to the database. - */ - password?: string; - /** - * The port of the database. - */ - port?: number; - /** - * The username to connect to the database. - */ - username?: string; + /** + * The connection timeout in seconds. + */ + connTimeoutSecs?: number; + /** + * The name of the database. + */ + database?: string; + /** + * The host of the database. + */ + host?: string; + /** + * The password to connect to the database. + */ + password?: string; + /** + * The port of the database. + */ + port?: number; + /** + * The username to connect to the database. + */ + username?: string; } /** * The configuration of the filesystem */ export interface PartialFilesConfiguration { - /** - * A list of Unix shell style patterns. Will ignore files/folders that will match these patterns. - */ - ignore?: StringSet; - /** - * A list of Unix shell style patterns. Will handle only those files/folders that will match these patterns. - */ - include?: StringSet; - /** - * The maximum allowed size for source code files in bytes. Files above this limit will be ignored for performance reasons. Defaults to 1 MiB - */ - maxSize?: number; + /** + * A list of Unix shell style patterns. Will ignore files/folders that will match these patterns. + */ + ignore?: StringSet; + /** + * A list of Unix shell style patterns. Will handle only those files/folders that will match these patterns. + */ + include?: StringSet; + /** + * The maximum allowed size for source code files in bytes. Files above this limit will be ignored for performance reasons. Defaults to 1 MiB + */ + maxSize?: number; } export interface PartialLinterConfiguration { - /** - * if `false`, it disables the feature and the linter won't be executed. `true` by default - */ - enabled?: boolean; - /** - * A list of Unix shell style patterns. The formatter will ignore files/folders that will match these patterns. - */ - ignore?: StringSet; - /** - * A list of Unix shell style patterns. The formatter will include files/folders that will match these patterns. - */ - include?: StringSet; - /** - * List of rules - */ - rules?: Rules; + /** + * if `false`, it disables the feature and the linter won't be executed. `true` by default + */ + enabled?: boolean; + /** + * A list of Unix shell style patterns. The formatter will ignore files/folders that will match these patterns. + */ + ignore?: StringSet; + /** + * A list of Unix shell style patterns. The formatter will include files/folders that will match these patterns. + */ + include?: StringSet; + /** + * List of rules + */ + rules?: Rules; } /** * The configuration of the filesystem */ export interface PartialMigrationsConfiguration { - /** - * Ignore any migrations before this timestamp - */ - after?: number; - /** - * The directory where the migration files are stored - */ - migrationsDir?: string; + /** + * Ignore any migrations before this timestamp + */ + after?: number; + /** + * The directory where the migration files are stored + */ + migrationsDir?: string; } /** * Set of properties to integrate with a VCS software. */ export interface PartialVcsConfiguration { - /** - * The kind of client. - */ - clientKind?: VcsClientKind; - /** - * The main branch of the project - */ - defaultBranch?: string; - /** - * Whether we should integrate itself with the VCS client - */ - enabled?: boolean; - /** + /** + * The kind of client. + */ + clientKind?: VcsClientKind; + /** + * The main branch of the project + */ + defaultBranch?: string; + /** + * Whether we should integrate itself with the VCS client + */ + enabled?: boolean; + /** * The folder where we should check for VCS files. By default, we will use the same folder where `postgrestools.jsonc` was found. If we can't find the configuration, it will attempt to use the current working directory. If no current working directory can't be found, we won't use the VCS integration, and a diagnostic will be emitted */ - root?: string; - /** - * Whether we should use the VCS ignore file. When [true], we will ignore the files specified in the ignore file. - */ - useIgnoreFile?: boolean; + root?: string; + /** + * Whether we should use the VCS ignore file. When [true], we will ignore the files specified in the ignore file. + */ + useIgnoreFile?: boolean; } export type StringSet = string[]; export interface Rules { - /** - * It enables ALL rules. The rules that belong to `nursery` won't be enabled. - */ - all?: boolean; - /** - * It enables the lint rules recommended by PostgresTools. `true` by default. - */ - recommended?: boolean; - safety?: Safety; + /** + * It enables ALL rules. The rules that belong to `nursery` won't be enabled. + */ + all?: boolean; + /** + * It enables the lint rules recommended by PostgresTools. `true` by default. + */ + recommended?: boolean; + safety?: Safety; } export type VcsClientKind = "git"; /** * A list of rules that belong to this group */ export interface Safety { - /** - * Adding a new column that is NOT NULL and has no default value to an existing table effectively makes it required. - */ - addingRequiredField?: RuleConfiguration_for_Null; - /** - * It enables ALL rules for this group. - */ - all?: boolean; - /** - * Dropping a column may break existing clients. - */ - banDropColumn?: RuleConfiguration_for_Null; - /** - * Dropping a NOT NULL constraint may break existing clients. - */ - banDropNotNull?: RuleConfiguration_for_Null; - /** - * Dropping a table may break existing clients. - */ - banDropTable?: RuleConfiguration_for_Null; - /** - * It enables the recommended rules for this group - */ - recommended?: boolean; + /** + * Adding a new column that is NOT NULL and has no default value to an existing table effectively makes it required. + */ + addingRequiredField?: RuleConfiguration_for_Null; + /** + * It enables ALL rules for this group. + */ + all?: boolean; + /** + * Dropping a column may break existing clients. + */ + banDropColumn?: RuleConfiguration_for_Null; + /** + * Dropping a NOT NULL constraint may break existing clients. + */ + banDropNotNull?: RuleConfiguration_for_Null; + /** + * Dropping a table may break existing clients. + */ + banDropTable?: RuleConfiguration_for_Null; + /** + * It enables the recommended rules for this group + */ + recommended?: boolean; } export type RuleConfiguration_for_Null = - | RulePlainConfiguration - | RuleWithOptions_for_Null; + | RulePlainConfiguration + | RuleWithOptions_for_Null; export type RulePlainConfiguration = "warn" | "error" | "info" | "off"; export interface RuleWithOptions_for_Null { - /** - * The severity of the emitted diagnostics by the rule - */ - level: RulePlainConfiguration; - /** - * Rule's options - */ - options: null; + /** + * The severity of the emitted diagnostics by the rule + */ + level: RulePlainConfiguration; + /** + * Rule's options + */ + options: null; } export interface OpenFileParams { - content: string; - path: PgLTPath; - version: number; + content: string; + path: PgLTPath; + version: number; } export interface ChangeFileParams { - changes: ChangeParams[]; - path: PgLTPath; - version: number; + changes: ChangeParams[]; + path: PgLTPath; + version: number; } export interface ChangeParams { - /** - * The range of the file that changed. If `None`, the whole file changed. - */ - range?: TextRange; - text: string; + /** + * The range of the file that changed. If `None`, the whole file changed. + */ + range?: TextRange; + text: string; } export interface CloseFileParams { - path: PgLTPath; + path: PgLTPath; } export type Configuration = PartialConfiguration; export interface Workspace { - isPathIgnored(params: IsPathIgnoredParams): Promise; - getFileContent(params: GetFileContentParams): Promise; - pullDiagnostics( - params: PullDiagnosticsParams - ): Promise; - getCompletions(params: GetCompletionsParams): Promise; - updateSettings(params: UpdateSettingsParams): Promise; - openFile(params: OpenFileParams): Promise; - changeFile(params: ChangeFileParams): Promise; - closeFile(params: CloseFileParams): Promise; - destroy(): void; + isPathIgnored(params: IsPathIgnoredParams): Promise; + getFileContent(params: GetFileContentParams): Promise; + pullDiagnostics( + params: PullDiagnosticsParams, + ): Promise; + getCompletions(params: GetCompletionsParams): Promise; + updateSettings(params: UpdateSettingsParams): Promise; + openFile(params: OpenFileParams): Promise; + changeFile(params: ChangeFileParams): Promise; + closeFile(params: CloseFileParams): Promise; + destroy(): void; } export function createWorkspace(transport: Transport): Workspace { - return { - isPathIgnored(params) { - return transport.request("pglt/is_path_ignored", params); - }, - getFileContent(params) { - return transport.request("pglt/get_file_content", params); - }, - pullDiagnostics(params) { - return transport.request("pglt/pull_diagnostics", params); - }, - getCompletions(params) { - return transport.request("pglt/get_completions", params); - }, - updateSettings(params) { - return transport.request("pglt/update_settings", params); - }, - openFile(params) { - return transport.request("pglt/open_file", params); - }, - changeFile(params) { - return transport.request("pglt/change_file", params); - }, - closeFile(params) { - return transport.request("pglt/close_file", params); - }, - destroy() { - transport.destroy(); - }, - }; + return { + isPathIgnored(params) { + return transport.request("pgt/is_path_ignored", params); + }, + getFileContent(params) { + return transport.request("pgt/get_file_content", params); + }, + pullDiagnostics(params) { + return transport.request("pgt/pull_diagnostics", params); + }, + getCompletions(params) { + return transport.request("pgt/get_completions", params); + }, + updateSettings(params) { + return transport.request("pgt/update_settings", params); + }, + openFile(params) { + return transport.request("pgt/open_file", params); + }, + changeFile(params) { + return transport.request("pgt/change_file", params); + }, + closeFile(params) { + return transport.request("pgt/close_file", params); + }, + destroy() { + transport.destroy(); + }, + }; } diff --git a/packages/@postgrestools/backend-jsonrpc/tests/workspace.test.mjs b/packages/@postgrestools/backend-jsonrpc/tests/workspace.test.mjs index efab4f56d..c83d5e44c 100644 --- a/packages/@postgrestools/backend-jsonrpc/tests/workspace.test.mjs +++ b/packages/@postgrestools/backend-jsonrpc/tests/workspace.test.mjs @@ -5,50 +5,50 @@ import { describe, expect, it } from "vitest"; import { createWorkspaceWithBinary } from "../dist"; describe("Workspace API", () => { - it("should process remote requests", async () => { - const extension = process.platform === "win32" ? ".exe" : ""; - const command = resolve( - fileURLToPath(import.meta.url), - "../../../../..", - `target/release/postgrestools${extension}` - ); + it("should process remote requests", async () => { + const extension = process.platform === "win32" ? ".exe" : ""; + const command = resolve( + fileURLToPath(import.meta.url), + "../../../../..", + `target/release/postgrestools${extension}`, + ); - const workspace = await createWorkspaceWithBinary(command); - await workspace.openFile({ - path: { - path: "test.sql", - was_written: false, - kind: ["Handleable"], - }, - content: "select 1 from", - version: 0, - }); + const workspace = await createWorkspaceWithBinary(command); + await workspace.openFile({ + path: { + path: "test.sql", + was_written: false, + kind: ["Handleable"], + }, + content: "select 1 from", + version: 0, + }); - const { diagnostics } = await workspace.pullDiagnostics({ - only: [], - skip: [], - max_diagnostics: 100, - categories: [], - path: { - path: "test.sql", - was_written: false, - kind: ["Handleable"], - }, - }); + const { diagnostics } = await workspace.pullDiagnostics({ + only: [], + skip: [], + max_diagnostics: 100, + categories: [], + path: { + path: "test.sql", + was_written: false, + kind: ["Handleable"], + }, + }); - expect(diagnostics).toHaveLength(1); - expect(diagnostics[0].description).toBe( - "Invalid statement: syntax error at end of input" - ); + expect(diagnostics).toHaveLength(1); + expect(diagnostics[0].description).toBe( + "Invalid statement: syntax error at end of input", + ); - await workspace.closeFile({ - path: { - path: "test.sql", - was_written: false, - kind: ["Handleable"], - }, - }); + await workspace.closeFile({ + path: { + path: "test.sql", + was_written: false, + kind: ["Handleable"], + }, + }); - workspace.destroy(); - }); + workspace.destroy(); + }); }); diff --git a/packages/@postgrestools/postgrestools/package.json b/packages/@postgrestools/postgrestools/package.json index 42f786d15..0d9ea38bd 100644 --- a/packages/@postgrestools/postgrestools/package.json +++ b/packages/@postgrestools/postgrestools/package.json @@ -1,43 +1,40 @@ { - "name": "postgrestools", - "version": "", - "bin": { - "postgrestools": "bin/postgrestools" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/supabase-community/postgres_lsp.git", - "directory": "packages/@postgrestools/postgrestools" - }, - "author": "Supabase Community", - "contributors": [ - { - "name": "Philipp Steinrötter", - "url": "https://github.com/psteinroe" - }, - { - "name": "Julian Domke", - "url": "https://github.com/juleswritescode" - } - ], - "license": "MIT or Apache-2.0", - "description": "A collection of language tools and a Language Server Protocol (LSP) implementation for Postgres, focusing on developer experience and reliable SQL tooling.", - "files": [ - "bin/postgrestools", - "schema.json" - ], - "engines": { - "node": ">=20" - }, - "publishConfig": { - "provenance": true - }, - "optionalDependencies": { - "postgrestools-x86_64-windows-msvc": "", - "postgrestools-aarch64-windows-msvc": "", - "postgrestools-x86_64-apple-darwin": "", - "postgrestools-aarch64-apple-darwin": "", - "postgrestools-x86_64-linux-gnu": "", - "postgrestools-aarch64-linux-gnu": "" - } + "name": "postgrestools", + "version": "", + "bin": { + "postgrestools": "bin/postgrestools" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/supabase-community/postgres_lsp.git", + "directory": "packages/@postgrestools/postgrestools" + }, + "author": "Supabase Community", + "contributors": [ + { + "name": "Philipp Steinrötter", + "url": "https://github.com/psteinroe" + }, + { + "name": "Julian Domke", + "url": "https://github.com/juleswritescode" + } + ], + "license": "MIT or Apache-2.0", + "description": "A collection of language tools and a Language Server Protocol (LSP) implementation for Postgres, focusing on developer experience and reliable SQL tooling.", + "files": ["bin/postgrestools", "schema.json"], + "engines": { + "node": ">=20" + }, + "publishConfig": { + "provenance": true + }, + "optionalDependencies": { + "postgrestools-x86_64-windows-msvc": "", + "postgrestools-aarch64-windows-msvc": "", + "postgrestools-x86_64-apple-darwin": "", + "postgrestools-aarch64-apple-darwin": "", + "postgrestools-x86_64-linux-gnu": "", + "postgrestools-aarch64-linux-gnu": "" + } } diff --git a/packages/@postgrestools/postgrestools/scripts/generate-packages.mjs b/packages/@postgrestools/postgrestools/scripts/generate-packages.mjs index 0be0138e4..b63a999af 100644 --- a/packages/@postgrestools/postgrestools/scripts/generate-packages.mjs +++ b/packages/@postgrestools/postgrestools/scripts/generate-packages.mjs @@ -10,247 +10,247 @@ const CLI_ROOT = resolve(fileURLToPath(import.meta.url), "../.."); const PACKAGES_POSTGRESTOOLS_ROOT = resolve(CLI_ROOT, ".."); const POSTGRESTOOLS_ROOT = resolve(PACKAGES_POSTGRESTOOLS_ROOT, "../.."); const SUPPORTED_PLATFORMS = [ - "pc-windows-msvc", - "apple-darwin", - "unknown-linux-gnu", + "pc-windows-msvc", + "apple-darwin", + "unknown-linux-gnu", ]; const SUPPORTED_ARCHITECTURES = ["x86_64", "aarch64"]; async function downloadSchema(releaseTag, githubToken) { - const assetUrl = `https://github.com/supabase-community/postgres_lsp/releases/download/${releaseTag}/schema.json`; + const assetUrl = `https://github.com/supabase-community/postgres_lsp/releases/download/${releaseTag}/schema.json`; - const response = await fetch(assetUrl.trim(), { - headers: { - Authorization: `token ${githubToken}`, - Accept: "application/octet-stream", - }, - }); + const response = await fetch(assetUrl.trim(), { + headers: { + Authorization: `token ${githubToken}`, + Accept: "application/octet-stream", + }, + }); - if (!response.ok) { - throw new Error(`Failed to Fetch Asset from ${assetUrl}`); - } + if (!response.ok) { + throw new Error(`Failed to Fetch Asset from ${assetUrl}`); + } - // download to root. - const fileStream = fs.createWriteStream( - resolve(POSTGRESTOOLS_ROOT, "schema.json") - ); + // download to root. + const fileStream = fs.createWriteStream( + resolve(POSTGRESTOOLS_ROOT, "schema.json"), + ); - await streamPipeline(response.body, fileStream); + await streamPipeline(response.body, fileStream); - console.log(`Downloaded schema for ${releaseTag}`); + console.log(`Downloaded schema for ${releaseTag}`); } async function downloadBinary(platform, arch, os, releaseTag, githubToken) { - const buildName = getBuildName(platform, arch); + const buildName = getBuildName(platform, arch); - const assetUrl = `https://github.com/supabase-community/postgres_lsp/releases/download/${releaseTag}/${buildName}`; + const assetUrl = `https://github.com/supabase-community/postgres_lsp/releases/download/${releaseTag}/${buildName}`; - const response = await fetch(assetUrl.trim(), { - headers: { - Authorization: `token ${githubToken}`, - Accept: "application/octet-stream", - }, - }); + const response = await fetch(assetUrl.trim(), { + headers: { + Authorization: `token ${githubToken}`, + Accept: "application/octet-stream", + }, + }); - if (!response.ok) { - const error = await response.text(); - throw new Error( - `Failed to Fetch Asset from ${assetUrl} (Reason: ${error})` - ); - } + if (!response.ok) { + const error = await response.text(); + throw new Error( + `Failed to Fetch Asset from ${assetUrl} (Reason: ${error})`, + ); + } - // just download to root. - const fileStream = fs.createWriteStream(getBinarySource(platform, arch, os)); + // just download to root. + const fileStream = fs.createWriteStream(getBinarySource(platform, arch, os)); - await streamPipeline(response.body, fileStream); + await streamPipeline(response.body, fileStream); - console.log(`Downloaded asset for ${buildName} (v${releaseTag})`); + console.log(`Downloaded asset for ${buildName} (v${releaseTag})`); } async function writeManifest(packagePath, version) { - const manifestPath = resolve( - PACKAGES_POSTGRESTOOLS_ROOT, - packagePath, - "package.json" - ); - - const manifestData = JSON.parse( - fs.readFileSync(manifestPath).toString("utf-8") - ); - - const nativePackages = SUPPORTED_PLATFORMS.flatMap((platform) => - SUPPORTED_ARCHITECTURES.map((arch) => [ - `@postgrestools/${getName(platform, arch)}`, - version, - ]) - ); - - manifestData.version = version; - manifestData.optionalDependencies = Object.fromEntries(nativePackages); - - console.log(`Update manifest ${manifestPath}`); - const content = JSON.stringify(manifestData, null, 2); - - /** - * writeFileSync seemed to not work reliably? - */ - await new Promise((res, rej) => { - fs.writeFile(manifestPath, content, (e) => (e ? rej(e) : res())); - }); + const manifestPath = resolve( + PACKAGES_POSTGRESTOOLS_ROOT, + packagePath, + "package.json", + ); + + const manifestData = JSON.parse( + fs.readFileSync(manifestPath).toString("utf-8"), + ); + + const nativePackages = SUPPORTED_PLATFORMS.flatMap((platform) => + SUPPORTED_ARCHITECTURES.map((arch) => [ + `@postgrestools/${getName(platform, arch)}`, + version, + ]), + ); + + manifestData.version = version; + manifestData.optionalDependencies = Object.fromEntries(nativePackages); + + console.log(`Update manifest ${manifestPath}`); + const content = JSON.stringify(manifestData, null, 2); + + /** + * writeFileSync seemed to not work reliably? + */ + await new Promise((res, rej) => { + fs.writeFile(manifestPath, content, (e) => (e ? rej(e) : res())); + }); } async function makePackageDir(platform, arch) { - const buildName = getBuildName(platform, arch); - const packageRoot = resolve(PACKAGES_POSTGRESTOOLS_ROOT, buildName); + const buildName = getBuildName(platform, arch); + const packageRoot = resolve(PACKAGES_POSTGRESTOOLS_ROOT, buildName); - await new Promise((res, rej) => { - fs.mkdir(packageRoot, {}, (e) => (e ? rej(e) : res())); - }); + await new Promise((res, rej) => { + fs.mkdir(packageRoot, {}, (e) => (e ? rej(e) : res())); + }); } function copyBinaryToNativePackage(platform, arch, os) { - // Update the package.json manifest - const buildName = getBuildName(platform, arch); - const packageRoot = resolve(PACKAGES_POSTGRESTOOLS_ROOT, buildName); - const packageName = getPackageName(platform, arch); - - const { version, license, repository, engines } = rootManifest(); - - /** - * We need to map rust triplets to NPM-known values. - * Otherwise, npm will abort the package installation. - */ - const npm_arch = arch === "aarch64" ? "arm64" : "x64"; - let libc = undefined; - let npm_os = undefined; - - switch (os) { - case "linux": { - libc = "gnu"; - npm_os = "linux"; - break; - } - case "windows": { - libc = "msvc"; - npm_os = "win32"; - break; - } - case "darwin": { - libc = undefined; - npm_os = "darwin"; - break; - } - default: { - throw new Error(`Unsupported os: ${os}`); - } - } - - const manifest = JSON.stringify( - { - name: packageName, - version, - license, - repository, - engines, - os: [npm_os], - cpu: [npm_arch], - libc, - }, - null, - 2 - ); - - const ext = getBinaryExt(os); - const manifestPath = resolve(packageRoot, "package.json"); - console.info(`Update manifest ${manifestPath}`); - fs.writeFileSync(manifestPath, manifest); - - // Copy the CLI binary - const binarySource = getBinarySource(platform, arch, os); - const binaryTarget = resolve(packageRoot, `postgrestools${ext}`); - - if (!fs.existsSync(binarySource)) { - console.error( - `Source for binary for ${buildName} not found at: ${binarySource}` - ); - process.exit(1); - } - - console.info(`Copy binary ${binaryTarget}`); - fs.copyFileSync(binarySource, binaryTarget); - fs.chmodSync(binaryTarget, 0o755); + // Update the package.json manifest + const buildName = getBuildName(platform, arch); + const packageRoot = resolve(PACKAGES_POSTGRESTOOLS_ROOT, buildName); + const packageName = getPackageName(platform, arch); + + const { version, license, repository, engines } = rootManifest(); + + /** + * We need to map rust triplets to NPM-known values. + * Otherwise, npm will abort the package installation. + */ + const npm_arch = arch === "aarch64" ? "arm64" : "x64"; + let libc = undefined; + let npm_os = undefined; + + switch (os) { + case "linux": { + libc = "gnu"; + npm_os = "linux"; + break; + } + case "windows": { + libc = "msvc"; + npm_os = "win32"; + break; + } + case "darwin": { + libc = undefined; + npm_os = "darwin"; + break; + } + default: { + throw new Error(`Unsupported os: ${os}`); + } + } + + const manifest = JSON.stringify( + { + name: packageName, + version, + license, + repository, + engines, + os: [npm_os], + cpu: [npm_arch], + libc, + }, + null, + 2, + ); + + const ext = getBinaryExt(os); + const manifestPath = resolve(packageRoot, "package.json"); + console.info(`Update manifest ${manifestPath}`); + fs.writeFileSync(manifestPath, manifest); + + // Copy the CLI binary + const binarySource = getBinarySource(platform, arch, os); + const binaryTarget = resolve(packageRoot, `postgrestools${ext}`); + + if (!fs.existsSync(binarySource)) { + console.error( + `Source for binary for ${buildName} not found at: ${binarySource}`, + ); + process.exit(1); + } + + console.info(`Copy binary ${binaryTarget}`); + fs.copyFileSync(binarySource, binaryTarget); + fs.chmodSync(binaryTarget, 0o755); } function copySchemaToNativePackage(platform, arch) { - const buildName = getBuildName(platform, arch); - const packageRoot = resolve(PACKAGES_POSTGRESTOOLS_ROOT, buildName); + const buildName = getBuildName(platform, arch); + const packageRoot = resolve(PACKAGES_POSTGRESTOOLS_ROOT, buildName); - const schemaSrc = resolve(POSTGRESTOOLS_ROOT, "schema.json"); - const schemaTarget = resolve(packageRoot, "schema.json"); + const schemaSrc = resolve(POSTGRESTOOLS_ROOT, "schema.json"); + const schemaTarget = resolve(packageRoot, "schema.json"); - if (!fs.existsSync(schemaSrc)) { - console.error(`schema.json not found at: ${schemaSrc}`); - process.exit(1); - } + if (!fs.existsSync(schemaSrc)) { + console.error(`schema.json not found at: ${schemaSrc}`); + process.exit(1); + } - console.info("Copying schema.json"); - fs.copyFileSync(schemaSrc, schemaTarget); - fs.chmodSync(schemaTarget, 0o666); + console.info("Copying schema.json"); + fs.copyFileSync(schemaSrc, schemaTarget); + fs.chmodSync(schemaTarget, 0o666); } const rootManifest = () => - JSON.parse(fs.readFileSync(MANIFEST_PATH).toString("utf-8")); + JSON.parse(fs.readFileSync(MANIFEST_PATH).toString("utf-8")); function getBinaryExt(os) { - return os === "windows" ? ".exe" : ""; + return os === "windows" ? ".exe" : ""; } function getBinarySource(platform, arch, os) { - const ext = getBinaryExt(os); - return resolve(POSTGRESTOOLS_ROOT, `${getBuildName(platform, arch)}${ext}`); + const ext = getBinaryExt(os); + return resolve(POSTGRESTOOLS_ROOT, `${getBuildName(platform, arch)}${ext}`); } function getBuildName(platform, arch) { - return `pglt_${arch}-${platform}`; + return `pglt_${arch}-${platform}`; } function getPackageName(platform, arch) { - // trim the "unknown" from linux and the "pc" from windows - const platformName = platform.split("-").slice(-2).join("-"); - return `postgrestools-${arch}-${platformName}`; + // trim the "unknown" from linux and the "pc" from windows + const platformName = platform.split("-").slice(-2).join("-"); + return `postgrestools-${arch}-${platformName}`; } function getOs(platform) { - return platform.split("-").find((_, idx) => idx === 1); + return platform.split("-").find((_, idx) => idx === 1); } function getVersion(releaseTag, isPrerelease) { - return releaseTag + (isPrerelease ? "-rc" : ""); + return releaseTag + (isPrerelease ? "-rc" : ""); } (async function main() { - const githubToken = process.env.GITHUB_TOKEN; - const releaseTag = process.env.RELEASE_TAG; - assert(githubToken, "GITHUB_TOKEN not defined!"); - assert(releaseTag, "RELEASE_TAG not defined!"); - - const isPrerelease = process.env.PRERELEASE === "true"; - - await downloadSchema(releaseTag, githubToken); - const version = getVersion(releaseTag, isPrerelease); - await writeManifest("postgrestools", version); - await writeManifest("backend-jsonrpc", version); - - for (const platform of SUPPORTED_PLATFORMS) { - const os = getOs(platform); - - for (const arch of SUPPORTED_ARCHITECTURES) { - await makePackageDir(platform, arch); - await downloadBinary(platform, arch, os, releaseTag, githubToken); - copyBinaryToNativePackage(platform, arch, os); - copySchemaToNativePackage(platform, arch); - } - } - - process.exit(0); + const githubToken = process.env.GITHUB_TOKEN; + const releaseTag = process.env.RELEASE_TAG; + assert(githubToken, "GITHUB_TOKEN not defined!"); + assert(releaseTag, "RELEASE_TAG not defined!"); + + const isPrerelease = process.env.PRERELEASE === "true"; + + await downloadSchema(releaseTag, githubToken); + const version = getVersion(releaseTag, isPrerelease); + await writeManifest("postgrestools", version); + await writeManifest("backend-jsonrpc", version); + + for (const platform of SUPPORTED_PLATFORMS) { + const os = getOs(platform); + + for (const arch of SUPPORTED_ARCHITECTURES) { + await makePackageDir(platform, arch); + await downloadBinary(platform, arch, os, releaseTag, githubToken); + copyBinaryToNativePackage(platform, arch, os); + copySchemaToNativePackage(platform, arch); + } + } + + process.exit(0); })(); From 7df2cbe7d53c81fdcabca0c9069685e4da0ab057 Mon Sep 17 00:00:00 2001 From: Julian Domke <68325451+juleswritescode@users.noreply.github.com> Date: Tue, 18 Mar 2025 13:23:43 +0100 Subject: [PATCH 3/3] chore: rename pglt in workflows (#242) * chore: rename pglt in workflows rename * chore: rename pglt_cli and binary (#243) * chore: rename pglt_cli and binary * docs * format * ok --- .github/workflows/publish.reusable.yml | 8 +- .github/workflows/pull_request.yml | 6 +- .github/workflows/release.yml | 14 +- Cargo.lock | 74 ++--- Cargo.toml | 2 +- crates/{pglt_cli => pgt_cli}/Cargo.toml | 4 +- crates/{pglt_cli => pgt_cli}/src/changed.rs | 0 .../{pglt_cli => pgt_cli}/src/cli_options.rs | 0 .../src/commands/check.rs | 0 .../src/commands/clean.rs | 0 .../src/commands/daemon.rs | 0 .../src/commands/init.rs | 0 .../{pglt_cli => pgt_cli}/src/commands/mod.rs | 2 +- .../src/commands/version.rs | 0 .../{pglt_cli => pgt_cli}/src/diagnostics.rs | 0 .../src/execute/diagnostics.rs | 0 .../{pglt_cli => pgt_cli}/src/execute/mod.rs | 0 .../src/execute/process_file.rs | 0 .../src/execute/process_file/check.rs | 0 .../execute/process_file/workspace_file.rs | 0 .../src/execute/std_in.rs | 0 .../src/execute/traverse.rs | 0 crates/{pglt_cli => pgt_cli}/src/lib.rs | 0 crates/{pglt_cli => pgt_cli}/src/logging.rs | 0 crates/{pglt_cli => pgt_cli}/src/main.rs | 8 +- crates/{pglt_cli => pgt_cli}/src/metrics.rs | 0 crates/{pglt_cli => pgt_cli}/src/panic.rs | 0 .../src/reporter/github.rs | 0 .../src/reporter/gitlab.rs | 0 .../src/reporter/junit.rs | 0 .../{pglt_cli => pgt_cli}/src/reporter/mod.rs | 0 .../src/reporter/terminal.rs | 0 .../{pglt_cli => pgt_cli}/src/service/mod.rs | 0 .../{pglt_cli => pgt_cli}/src/service/unix.rs | 0 .../src/service/windows.rs | 0 docs/cli_reference.md | 259 ++++++++---------- docs/codegen/Cargo.toml | 2 +- docs/codegen/src/cli_doc.rs | 2 +- .../backend-jsonrpc/src/workspace.ts | 16 +- xtask/src/install.rs | 2 +- 40 files changed, 190 insertions(+), 209 deletions(-) rename crates/{pglt_cli => pgt_cli}/Cargo.toml (97%) rename crates/{pglt_cli => pgt_cli}/src/changed.rs (100%) rename crates/{pglt_cli => pgt_cli}/src/cli_options.rs (100%) rename crates/{pglt_cli => pgt_cli}/src/commands/check.rs (100%) rename crates/{pglt_cli => pgt_cli}/src/commands/clean.rs (100%) rename crates/{pglt_cli => pgt_cli}/src/commands/daemon.rs (100%) rename crates/{pglt_cli => pgt_cli}/src/commands/init.rs (100%) rename crates/{pglt_cli => pgt_cli}/src/commands/mod.rs (99%) rename crates/{pglt_cli => pgt_cli}/src/commands/version.rs (100%) rename crates/{pglt_cli => pgt_cli}/src/diagnostics.rs (100%) rename crates/{pglt_cli => pgt_cli}/src/execute/diagnostics.rs (100%) rename crates/{pglt_cli => pgt_cli}/src/execute/mod.rs (100%) rename crates/{pglt_cli => pgt_cli}/src/execute/process_file.rs (100%) rename crates/{pglt_cli => pgt_cli}/src/execute/process_file/check.rs (100%) rename crates/{pglt_cli => pgt_cli}/src/execute/process_file/workspace_file.rs (100%) rename crates/{pglt_cli => pgt_cli}/src/execute/std_in.rs (100%) rename crates/{pglt_cli => pgt_cli}/src/execute/traverse.rs (100%) rename crates/{pglt_cli => pgt_cli}/src/lib.rs (100%) rename crates/{pglt_cli => pgt_cli}/src/logging.rs (100%) rename crates/{pglt_cli => pgt_cli}/src/main.rs (99%) rename crates/{pglt_cli => pgt_cli}/src/metrics.rs (100%) rename crates/{pglt_cli => pgt_cli}/src/panic.rs (100%) rename crates/{pglt_cli => pgt_cli}/src/reporter/github.rs (100%) rename crates/{pglt_cli => pgt_cli}/src/reporter/gitlab.rs (100%) rename crates/{pglt_cli => pgt_cli}/src/reporter/junit.rs (100%) rename crates/{pglt_cli => pgt_cli}/src/reporter/mod.rs (100%) rename crates/{pglt_cli => pgt_cli}/src/reporter/terminal.rs (100%) rename crates/{pglt_cli => pgt_cli}/src/service/mod.rs (100%) rename crates/{pglt_cli => pgt_cli}/src/service/unix.rs (100%) rename crates/{pglt_cli => pgt_cli}/src/service/windows.rs (100%) diff --git a/.github/workflows/publish.reusable.yml b/.github/workflows/publish.reusable.yml index 3d85b3c1f..a06ff8af8 100644 --- a/.github/workflows/publish.reusable.yml +++ b/.github/workflows/publish.reusable.yml @@ -29,7 +29,7 @@ jobs: - name: Generate Packages id: generate-packages - run: node packages/@pglt/pglt/scripts/generate-packages.mjs + run: node packages/@postgrestools/postgrestools/scripts/generate-packages.mjs env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} RELEASE_TAG: ${{ inputs.release-tag }} @@ -46,12 +46,12 @@ jobs: - name: Print package.json run: | - cat packages/@pglt/pglt/package.json + cat packages/@postgrestools/postgrestools/package.json - name: Publish npm packages as nightly if: inputs.is-prerelease == 'true' run: | - for package in packages/@pglt/*; do + for package in packages/@postgrestools/*; do npm publish "$package" --tag nightly --access public --provenance done env: @@ -60,7 +60,7 @@ jobs: - name: Publish npm packages as latest if: inputs.is-prerelease != 'true' run: | - for package in packages/@pglt/*; do + for package in packages/@postgrestools/*; do npm publish "$package" --tag latest --access public --provenance done env: diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index 1a0839ce1..47426d049 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -153,16 +153,16 @@ jobs: - name: Install toolchain uses: moonrepo/setup-rust@v1 - name: Build main binary - run: cargo build -p pglt_cli --release + run: cargo build -p pgt_cli --release - name: Setup Bun uses: oven-sh/setup-bun@v2 - name: Install JS dependencies run: bun install - name: Build TypeScript code - working-directory: packages/@pglt/backend-jsonrpc + working-directory: packages/@postgrestools/backend-jsonrpc run: bun run build - name: Run JS tests - working-directory: packages/@pglt/backend-jsonrpc + working-directory: packages/@postgrestools/backend-jsonrpc run: bun run test codegen: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 882dd01d8..1489f53c5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -61,19 +61,19 @@ jobs: DATABASE_URL: postgres://postgres:postgres@localhost:5432/postgres - name: 🛠️ Run Build - run: cargo build -p pglt_cli --release --target ${{ matrix.config.target }} + run: cargo build -p pgt_cli --release --target ${{ matrix.config.target }} # windows is a special snowflake too, it saves binaries as .exe - name: 👦 Name the Binary if: matrix.config.os == 'windows-latest' run: | mkdir dist - cp target/${{ matrix.config.target }}/release/pglt.exe ./dist/pglt_${{ matrix.config.target }} + cp target/${{ matrix.config.target }}/release/postgrestools.exe ./dist/postgrestools_${{ matrix.config.target }} - name: 👦 Name the Binary if: matrix.config.os != 'windows-latest' run: | mkdir dist - cp target/${{ matrix.config.target }}/release/pglt ./dist/pglt_${{ matrix.config.target }} + cp target/${{ matrix.config.target }}/release/postgrestools ./dist/postgrestools_${{ matrix.config.target }} # It is not possible to return the artifacts from the matrix jobs individually: Matrix outputs overwrite each other. # A common workaround is to upload and download the resulting artifacts. @@ -81,8 +81,8 @@ jobs: id: upload-artifacts uses: actions/upload-artifact@v4 with: - name: pglt_${{ matrix.config.target }} - path: ./dist/pglt_* + name: postgrestools_${{ matrix.config.target }} + path: ./dist/postgrestools_* # The default compression level is 6; this took the binary down from 350 to 330MB. # It is recommended to use a lower level for binaries, since the compressed result is not much smaller, # and the higher levels of compression take much longer. @@ -113,7 +113,7 @@ jobs: id: download with: merge-multiple: true - pattern: pglt_* + pattern: postgrestools_* - name: 📂 Create Release uses: softprops/action-gh-release@v2 @@ -125,7 +125,7 @@ jobs: body: ${{ steps.create_changelog.outputs.content }} tag_name: ${{ steps.create_changelog.outputs.version }} files: | - pglt_* + postgrestools_* docs/schemas/latest/schema.json fail_on_unmatched_files: true draft: true diff --git a/Cargo.lock b/Cargo.lock index c40f1910b..e7c7fb482 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1043,7 +1043,6 @@ dependencies = [ "bpaf", "pglt_analyse", "pglt_analyser", - "pglt_cli", "pglt_configuration", "pglt_console", "pglt_diagnostics", @@ -1051,6 +1050,7 @@ dependencies = [ "pglt_query_ext", "pglt_statement_splitter", "pglt_workspace", + "pgt_cli", "pulldown-cmark", "regex", "schemars", @@ -2338,42 +2338,6 @@ dependencies = [ "termcolor", ] -[[package]] -name = "pglt_cli" -version = "0.0.0" -dependencies = [ - "anyhow", - "biome_deserialize 0.6.0", - "biome_deserialize_macros 0.6.0", - "bpaf", - "crossbeam", - "dashmap 5.5.3", - "hdrhistogram", - "libc", - "mimalloc", - "path-absolutize", - "pglt_analyse", - "pglt_configuration", - "pglt_console", - "pglt_diagnostics", - "pglt_flags", - "pglt_fs", - "pglt_lsp", - "pglt_text_edit", - "pglt_workspace", - "quick-junit", - "rayon", - "rustc-hash 2.1.0", - "serde", - "serde_json", - "tikv-jemallocator", - "tokio", - "tracing", - "tracing-appender", - "tracing-subscriber", - "tracing-tree", -] - [[package]] name = "pglt_commands" version = "0.0.0" @@ -2736,6 +2700,42 @@ dependencies = [ "tree_sitter_sql", ] +[[package]] +name = "pgt_cli" +version = "0.0.0" +dependencies = [ + "anyhow", + "biome_deserialize 0.6.0", + "biome_deserialize_macros 0.6.0", + "bpaf", + "crossbeam", + "dashmap 5.5.3", + "hdrhistogram", + "libc", + "mimalloc", + "path-absolutize", + "pglt_analyse", + "pglt_configuration", + "pglt_console", + "pglt_diagnostics", + "pglt_flags", + "pglt_fs", + "pglt_lsp", + "pglt_text_edit", + "pglt_workspace", + "quick-junit", + "rayon", + "rustc-hash 2.1.0", + "serde", + "serde_json", + "tikv-jemallocator", + "tokio", + "tracing", + "tracing-appender", + "tracing-subscriber", + "tracing-tree", +] + [[package]] name = "pin-project" version = "1.1.7" diff --git a/Cargo.toml b/Cargo.toml index 3f7fbffac..42fffe71d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -54,7 +54,6 @@ unicode-width = "0.1.12" pglt_analyse = { path = "./crates/pglt_analyse", version = "0.0.0" } pglt_analyser = { path = "./crates/pglt_analyser", version = "0.0.0" } pglt_base_db = { path = "./crates/pglt_base_db", version = "0.0.0" } -pglt_cli = { path = "./crates/pglt_cli", version = "0.0.0" } pglt_commands = { path = "./crates/pglt_commands", version = "0.0.0" } pglt_completions = { path = "./crates/pglt_completions", version = "0.0.0" } pglt_configuration = { path = "./crates/pglt_configuration", version = "0.0.0" } @@ -81,6 +80,7 @@ pglt_treesitter_queries = { path = "./crates/pglt_treesitter_queries", versi pglt_type_resolver = { path = "./crates/pglt_type_resolver", version = "0.0.0" } pglt_typecheck = { path = "./crates/pglt_typecheck", version = "0.0.0" } pglt_workspace = { path = "./crates/pglt_workspace", version = "0.0.0" } +pgt_cli = { path = "./crates/pgt_cli", version = "0.0.0" } pglt_test_macros = { path = "./crates/pglt_test_macros" } pglt_test_utils = { path = "./crates/pglt_test_utils" } diff --git a/crates/pglt_cli/Cargo.toml b/crates/pgt_cli/Cargo.toml similarity index 97% rename from crates/pglt_cli/Cargo.toml rename to crates/pgt_cli/Cargo.toml index 204d20918..7c6e6779a 100644 --- a/crates/pglt_cli/Cargo.toml +++ b/crates/pgt_cli/Cargo.toml @@ -6,7 +6,7 @@ edition.workspace = true homepage.workspace = true keywords.workspace = true license.workspace = true -name = "pglt_cli" +name = "pgt_cli" repository.workspace = true version = "0.0.0" @@ -56,5 +56,5 @@ tikv-jemallocator = "0.6.0" doctest = false [[bin]] -name = "pglt" +name = "postgrestools" path = "src/main.rs" diff --git a/crates/pglt_cli/src/changed.rs b/crates/pgt_cli/src/changed.rs similarity index 100% rename from crates/pglt_cli/src/changed.rs rename to crates/pgt_cli/src/changed.rs diff --git a/crates/pglt_cli/src/cli_options.rs b/crates/pgt_cli/src/cli_options.rs similarity index 100% rename from crates/pglt_cli/src/cli_options.rs rename to crates/pgt_cli/src/cli_options.rs diff --git a/crates/pglt_cli/src/commands/check.rs b/crates/pgt_cli/src/commands/check.rs similarity index 100% rename from crates/pglt_cli/src/commands/check.rs rename to crates/pgt_cli/src/commands/check.rs diff --git a/crates/pglt_cli/src/commands/clean.rs b/crates/pgt_cli/src/commands/clean.rs similarity index 100% rename from crates/pglt_cli/src/commands/clean.rs rename to crates/pgt_cli/src/commands/clean.rs diff --git a/crates/pglt_cli/src/commands/daemon.rs b/crates/pgt_cli/src/commands/daemon.rs similarity index 100% rename from crates/pglt_cli/src/commands/daemon.rs rename to crates/pgt_cli/src/commands/daemon.rs diff --git a/crates/pglt_cli/src/commands/init.rs b/crates/pgt_cli/src/commands/init.rs similarity index 100% rename from crates/pglt_cli/src/commands/init.rs rename to crates/pgt_cli/src/commands/init.rs diff --git a/crates/pglt_cli/src/commands/mod.rs b/crates/pgt_cli/src/commands/mod.rs similarity index 99% rename from crates/pglt_cli/src/commands/mod.rs rename to crates/pgt_cli/src/commands/mod.rs index 16b7b9768..2799fc3bc 100644 --- a/crates/pglt_cli/src/commands/mod.rs +++ b/crates/pgt_cli/src/commands/mod.rs @@ -43,7 +43,7 @@ pub enum PgltCommand { /// /// The file doesn't need to exist on disk, what matters is the extension of the file. Based on the extension, we know how to check the code. /// - /// Example: `echo 'let a;' | pglt_cli check --stdin-file-path=test.sql` + /// Example: `echo 'let a;' | pgt_cli check --stdin-file-path=test.sql` #[bpaf(long("stdin-file-path"), argument("PATH"), hide_usage)] stdin_file_path: Option, diff --git a/crates/pglt_cli/src/commands/version.rs b/crates/pgt_cli/src/commands/version.rs similarity index 100% rename from crates/pglt_cli/src/commands/version.rs rename to crates/pgt_cli/src/commands/version.rs diff --git a/crates/pglt_cli/src/diagnostics.rs b/crates/pgt_cli/src/diagnostics.rs similarity index 100% rename from crates/pglt_cli/src/diagnostics.rs rename to crates/pgt_cli/src/diagnostics.rs diff --git a/crates/pglt_cli/src/execute/diagnostics.rs b/crates/pgt_cli/src/execute/diagnostics.rs similarity index 100% rename from crates/pglt_cli/src/execute/diagnostics.rs rename to crates/pgt_cli/src/execute/diagnostics.rs diff --git a/crates/pglt_cli/src/execute/mod.rs b/crates/pgt_cli/src/execute/mod.rs similarity index 100% rename from crates/pglt_cli/src/execute/mod.rs rename to crates/pgt_cli/src/execute/mod.rs diff --git a/crates/pglt_cli/src/execute/process_file.rs b/crates/pgt_cli/src/execute/process_file.rs similarity index 100% rename from crates/pglt_cli/src/execute/process_file.rs rename to crates/pgt_cli/src/execute/process_file.rs diff --git a/crates/pglt_cli/src/execute/process_file/check.rs b/crates/pgt_cli/src/execute/process_file/check.rs similarity index 100% rename from crates/pglt_cli/src/execute/process_file/check.rs rename to crates/pgt_cli/src/execute/process_file/check.rs diff --git a/crates/pglt_cli/src/execute/process_file/workspace_file.rs b/crates/pgt_cli/src/execute/process_file/workspace_file.rs similarity index 100% rename from crates/pglt_cli/src/execute/process_file/workspace_file.rs rename to crates/pgt_cli/src/execute/process_file/workspace_file.rs diff --git a/crates/pglt_cli/src/execute/std_in.rs b/crates/pgt_cli/src/execute/std_in.rs similarity index 100% rename from crates/pglt_cli/src/execute/std_in.rs rename to crates/pgt_cli/src/execute/std_in.rs diff --git a/crates/pglt_cli/src/execute/traverse.rs b/crates/pgt_cli/src/execute/traverse.rs similarity index 100% rename from crates/pglt_cli/src/execute/traverse.rs rename to crates/pgt_cli/src/execute/traverse.rs diff --git a/crates/pglt_cli/src/lib.rs b/crates/pgt_cli/src/lib.rs similarity index 100% rename from crates/pglt_cli/src/lib.rs rename to crates/pgt_cli/src/lib.rs diff --git a/crates/pglt_cli/src/logging.rs b/crates/pgt_cli/src/logging.rs similarity index 100% rename from crates/pglt_cli/src/logging.rs rename to crates/pgt_cli/src/logging.rs diff --git a/crates/pglt_cli/src/main.rs b/crates/pgt_cli/src/main.rs similarity index 99% rename from crates/pglt_cli/src/main.rs rename to crates/pgt_cli/src/main.rs index c79f5ab0b..dcdc1096e 100644 --- a/crates/pglt_cli/src/main.rs +++ b/crates/pgt_cli/src/main.rs @@ -1,12 +1,12 @@ //! This is the main binary -use pglt_cli::{ - CliDiagnostic, CliSession, PgltCommand, open_transport, pglt_command, setup_panic_handler, - to_color_mode, -}; use pglt_console::{ConsoleExt, EnvConsole, markup}; use pglt_diagnostics::{Diagnostic, PrintDiagnostic, set_bottom_frame}; use pglt_workspace::workspace; +use pgt_cli::{ + CliDiagnostic, CliSession, PgltCommand, open_transport, pglt_command, setup_panic_handler, + to_color_mode, +}; use std::process::{ExitCode, Termination}; use tokio::runtime::Runtime; diff --git a/crates/pglt_cli/src/metrics.rs b/crates/pgt_cli/src/metrics.rs similarity index 100% rename from crates/pglt_cli/src/metrics.rs rename to crates/pgt_cli/src/metrics.rs diff --git a/crates/pglt_cli/src/panic.rs b/crates/pgt_cli/src/panic.rs similarity index 100% rename from crates/pglt_cli/src/panic.rs rename to crates/pgt_cli/src/panic.rs diff --git a/crates/pglt_cli/src/reporter/github.rs b/crates/pgt_cli/src/reporter/github.rs similarity index 100% rename from crates/pglt_cli/src/reporter/github.rs rename to crates/pgt_cli/src/reporter/github.rs diff --git a/crates/pglt_cli/src/reporter/gitlab.rs b/crates/pgt_cli/src/reporter/gitlab.rs similarity index 100% rename from crates/pglt_cli/src/reporter/gitlab.rs rename to crates/pgt_cli/src/reporter/gitlab.rs diff --git a/crates/pglt_cli/src/reporter/junit.rs b/crates/pgt_cli/src/reporter/junit.rs similarity index 100% rename from crates/pglt_cli/src/reporter/junit.rs rename to crates/pgt_cli/src/reporter/junit.rs diff --git a/crates/pglt_cli/src/reporter/mod.rs b/crates/pgt_cli/src/reporter/mod.rs similarity index 100% rename from crates/pglt_cli/src/reporter/mod.rs rename to crates/pgt_cli/src/reporter/mod.rs diff --git a/crates/pglt_cli/src/reporter/terminal.rs b/crates/pgt_cli/src/reporter/terminal.rs similarity index 100% rename from crates/pglt_cli/src/reporter/terminal.rs rename to crates/pgt_cli/src/reporter/terminal.rs diff --git a/crates/pglt_cli/src/service/mod.rs b/crates/pgt_cli/src/service/mod.rs similarity index 100% rename from crates/pglt_cli/src/service/mod.rs rename to crates/pgt_cli/src/service/mod.rs diff --git a/crates/pglt_cli/src/service/unix.rs b/crates/pgt_cli/src/service/unix.rs similarity index 100% rename from crates/pglt_cli/src/service/unix.rs rename to crates/pgt_cli/src/service/unix.rs diff --git a/crates/pglt_cli/src/service/windows.rs b/crates/pgt_cli/src/service/windows.rs similarity index 100% rename from crates/pglt_cli/src/service/windows.rs rename to crates/pgt_cli/src/service/windows.rs diff --git a/docs/cli_reference.md b/docs/cli_reference.md index 919b0d3e3..8779372af 100644 --- a/docs/cli_reference.md +++ b/docs/cli_reference.md @@ -1,289 +1,270 @@ ## CLI Reference -[//]: # (BEGIN CLI_REF) - - +[//]: # "BEGIN CLI_REF" # Command summary - * [`pglt`↴](#pglt) - * [`pglt version`↴](#pglt-version) - * [`pglt check`↴](#pglt-check) - * [`pglt start`↴](#pglt-start) - * [`pglt stop`↴](#pglt-stop) - * [`pglt init`↴](#pglt-init) - * [`pglt lsp-proxy`↴](#pglt-lsp-proxy) - * [`pglt clean`↴](#pglt-clean) +- [`postgrestools`↴](#postgrestools) +- [`postgrestools version`↴](#postgrestools-version) +- [`postgrestools check`↴](#postgrestools-check) +- [`postgrestools start`↴](#postgrestools-start) +- [`postgrestools stop`↴](#postgrestools-stop) +- [`postgrestools init`↴](#postgrestools-init) +- [`postgrestools lsp-proxy`↴](#postgrestools-lsp-proxy) +- [`postgrestools clean`↴](#postgrestools-clean) -## pglt +## postgrestools -PgLT official CLI. Use it to check the health of your project or run it to check single files. +PostgresTools official CLI. Use it to check the health of your project or run it to check single files. -**Usage**: **`pglt`** _`COMMAND ...`_ +**Usage**: **`postgrestools`** _`COMMAND ...`_ **Available options:** -- **`-h`**, **`--help`** — + +- **`-h`**, **`--help`** — Prints help information -- **`-V`**, **`--version`** — +- **`-V`**, **`--version`** — Prints version information - - **Available commands:** -- **`version`** — + +- **`version`** — Shows the version information and quit. -- **`check`** — +- **`check`** — Runs everything to the requested files. -- **`start`** — +- **`start`** — Starts the daemon server process. -- **`stop`** — +- **`stop`** — Stops the daemon server process. -- **`init`** — +- **`init`** — Bootstraps a new project. Creates a configuration file with some defaults. -- **`lsp-proxy`** — +- **`lsp-proxy`** — Acts as a server for the Language Server Protocol over stdin/stdout. -- **`clean`** — +- **`clean`** — Cleans the logs emitted by the daemon. - -## pglt version +## postgrestools version Shows the version information and quit. -**Usage**: **`pglt`** **`version`** +**Usage**: **`postgrestools`** **`version`** **Global options applied to all commands** -- **` --colors`**=_``_ — + +- **` --colors`**=_``_ — Set the formatting mode for markup: "off" prints everything as plain text, "force" forces the formatting of markup using ANSI even if the console output is determined to be incompatible -- **` --use-server`** — +- **` --use-server`** — Connect to a running instance of the daemon server. -- **` --skip-db`** — +- **` --skip-db`** — Skip connecting to the database and only run checks that don't require a database connection. -- **` --verbose`** — +- **` --verbose`** — Print additional diagnostics, and some diagnostics show more information. Also, print out what files were processed and which ones were modified. -- **` --config-path`**=_`PATH`_ — - Set the file path to the configuration file, or the directory path to find `pglt.jsonc`. If used, it disables the default configuration file resolution. -- **` --max-diagnostics`**=_`>`_ — +- **` --config-path`**=_`PATH`_ — + Set the file path to the configuration file, or the directory path to find `postgrestools.jsonc`. If used, it disables the default configuration file resolution. +- **` --max-diagnostics`**=_`>`_ — Cap the amount of diagnostics displayed. When `none` is provided, the limit is lifted. - [default: 20] -- **` --skip-errors`** — +- **` --skip-errors`** — Skip over files containing syntax errors instead of emitting an error diagnostic. -- **` --no-errors-on-unmatched`** — +- **` --no-errors-on-unmatched`** — Silence errors that would be emitted in case no files were processed during the execution of the command. -- **` --error-on-warnings`** — +- **` --error-on-warnings`** — Tell PgLT to exit with an error code if some diagnostics emit warnings. -- **` --reporter`**=_``_ — +- **` --reporter`**=_``_ — Allows to change how diagnostics and summary are reported. -- **` --log-level`**=_``_ — +- **` --log-level`**=_``_ — The level of logging. In order, from the most verbose to the least verbose: debug, info, warn, error. The value `none` won't show any logging. - + [default: none] -- **` --log-kind`**=_``_ — + +- **` --log-kind`**=_``_ — How the log should look like. - [default: pretty] -- **` --diagnostic-level`**=_``_ — +- **` --diagnostic-level`**=_``_ — The level of diagnostics to show. In order, from the lowest to the most important: info, warn, error. Passing `--diagnostic-level=error` will cause PgLT to print only diagnostics that contain only errors. - [default: info] - - **Available options:** -- **`-h`**, **`--help`** — - Prints help information +- **`-h`**, **`--help`** — + Prints help information -## pglt check +## postgrestools check Runs everything to the requested files. -**Usage**: **`pglt`** **`check`** \[**`--staged`**\] \[**`--changed`**\] \[**`--since`**=_`REF`_\] \[_`PATH`_\]... +**Usage**: **`postgrestools`** **`check`** \[**`--staged`**\] \[**`--changed`**\] \[**`--since`**=_`REF`_\] \[_`PATH`_\]... **The configuration that is contained inside the configuration file.** -- **` --vcs-enabled`**=_``_ — + +- **` --vcs-enabled`**=_``_ — Whether we should integrate itself with the VCS client -- **` --vcs-client-kind`**=_``_ — +- **` --vcs-client-kind`**=_``_ — The kind of client. -- **` --vcs-use-ignore-file`**=_``_ — +- **` --vcs-use-ignore-file`**=_``_ — Whether we should use the VCS ignore file. When [true], we will ignore the files specified in the ignore file. -- **` --vcs-root`**=_`PATH`_ — - The folder where we should check for VCS files. By default, we will use the same folder where `pglt.jsonc` was found. +- **` --vcs-root`**=_`PATH`_ — + The folder where we should check for VCS files. By default, we will use the same folder where `postgrestools.jsonc` was found. If we can't find the configuration, it will attempt to use the current working directory. If no current working directory can't be found, we won't use the VCS integration, and a diagnostic will be emitted -- **` --vcs-default-branch`**=_`BRANCH`_ — + +- **` --vcs-default-branch`**=_`BRANCH`_ — The main branch of the project -- **` --files-max-size`**=_`NUMBER`_ — +- **` --files-max-size`**=_`NUMBER`_ — The maximum allowed size for source code files in bytes. Files above this limit will be ignored for performance reasons. Defaults to 1 MiB -- **` --migrations-dir`**=_`ARG`_ — +- **` --migrations-dir`**=_`ARG`_ — The directory where the migration files are stored -- **` --after`**=_`ARG`_ — +- **` --after`**=_`ARG`_ — Ignore any migrations before this timestamp -- **` --host`**=_`ARG`_ — +- **` --host`**=_`ARG`_ — The host of the database. -- **` --port`**=_`ARG`_ — +- **` --port`**=_`ARG`_ — The port of the database. -- **` --username`**=_`ARG`_ — +- **` --username`**=_`ARG`_ — The username to connect to the database. -- **` --password`**=_`ARG`_ — +- **` --password`**=_`ARG`_ — The password to connect to the database. -- **` --database`**=_`ARG`_ — +- **` --database`**=_`ARG`_ — The name of the database. -- **` --conn_timeout_secs`**=_`ARG`_ — +- **` --conn_timeout_secs`**=_`ARG`_ — The connection timeout in seconds. - [default: Some(10)] - - **Global options applied to all commands** -- **` --colors`**=_``_ — + +- **` --colors`**=_``_ — Set the formatting mode for markup: "off" prints everything as plain text, "force" forces the formatting of markup using ANSI even if the console output is determined to be incompatible -- **` --use-server`** — +- **` --use-server`** — Connect to a running instance of the daemon server. -- **` --skip-db`** — +- **` --skip-db`** — Skip connecting to the database and only run checks that don't require a database connection. -- **` --verbose`** — +- **` --verbose`** — Print additional diagnostics, and some diagnostics show more information. Also, print out what files were processed and which ones were modified. -- **` --config-path`**=_`PATH`_ — - Set the file path to the configuration file, or the directory path to find `pglt.jsonc`. If used, it disables the default configuration file resolution. -- **` --max-diagnostics`**=_`>`_ — +- **` --config-path`**=_`PATH`_ — + Set the file path to the configuration file, or the directory path to find `postgrestools.jsonc`. If used, it disables the default configuration file resolution. +- **` --max-diagnostics`**=_`>`_ — Cap the amount of diagnostics displayed. When `none` is provided, the limit is lifted. - [default: 20] -- **` --skip-errors`** — +- **` --skip-errors`** — Skip over files containing syntax errors instead of emitting an error diagnostic. -- **` --no-errors-on-unmatched`** — +- **` --no-errors-on-unmatched`** — Silence errors that would be emitted in case no files were processed during the execution of the command. -- **` --error-on-warnings`** — +- **` --error-on-warnings`** — Tell PgLT to exit with an error code if some diagnostics emit warnings. -- **` --reporter`**=_``_ — +- **` --reporter`**=_``_ — Allows to change how diagnostics and summary are reported. -- **` --log-level`**=_``_ — +- **` --log-level`**=_``_ — The level of logging. In order, from the most verbose to the least verbose: debug, info, warn, error. The value `none` won't show any logging. - + [default: none] -- **` --log-kind`**=_``_ — + +- **` --log-kind`**=_``_ — How the log should look like. - [default: pretty] -- **` --diagnostic-level`**=_``_ — +- **` --diagnostic-level`**=_``_ — The level of diagnostics to show. In order, from the lowest to the most important: info, warn, error. Passing `--diagnostic-level=error` will cause PgLT to print only diagnostics that contain only errors. - [default: info] - - **Available positional items:** -- _`PATH`_ — - Single file, single path or list of paths - +- _`PATH`_ — + Single file, single path or list of paths **Available options:** -- **` --stdin-file-path`**=_`PATH`_ — + +- **` --stdin-file-path`**=_`PATH`_ — Use this option when you want to format code piped from `stdin`, and print the output to `stdout`. The file doesn't need to exist on disk, what matters is the extension of the file. Based on the extension, we know how to check the code. - Example: `echo 'let a;' | pglt_cli check --stdin-file-path=test.sql` -- **` --staged`** — + Example: `echo 'let a;' | pgt_cli check --stdin-file-path=test.sql` + +- **` --staged`** — When set to true, only the files that have been staged (the ones prepared to be committed) will be linted. This option should be used when working locally. -- **` --changed`** — +- **` --changed`** — When set to true, only the files that have been changed compared to your `defaultBranch` configuration will be linted. This option should be used in CI environments. -- **` --since`**=_`REF`_ — - Use this to specify the base branch to compare against when you're using the --changed flag and the `defaultBranch` is not set in your `pglt.jsonc` -- **`-h`**, **`--help`** — +- **` --since`**=_`REF`_ — + Use this to specify the base branch to compare against when you're using the --changed flag and the `defaultBranch` is not set in your `postgrestools.jsonc` +- **`-h`**, **`--help`** — Prints help information - -## pglt start +## postgrestools start Starts the daemon server process. -**Usage**: **`pglt`** **`start`** \[**`--config-path`**=_`PATH`_\] +**Usage**: **`postgrestools`** **`start`** \[**`--config-path`**=_`PATH`_\] **Available options:** -- **` --log-prefix-name`**=_`STRING`_ — + +- **` --log-prefix-name`**=_`STRING`_ — Allows to change the prefix applied to the file name of the logs. - Uses environment variable **`PGLT_LOG_PREFIX_NAME`** - [default: server.log] -- **` --log-path`**=_`PATH`_ — +- **` --log-path`**=_`PATH`_ — Allows to change the folder where logs are stored. - Uses environment variable **`PGLT_LOG_PATH`** -- **` --config-path`**=_`PATH`_ — - Allows to set a custom file path to the configuration file, or a custom directory path to find `pglt.jsonc` - +- **` --config-path`**=_`PATH`_ — + Allows to set a custom file path to the configuration file, or a custom directory path to find `postgrestools.jsonc` Uses environment variable **`PGLT_LOG_PREFIX_NAME`** -- **`-h`**, **`--help`** — +- **`-h`**, **`--help`** — Prints help information - -## pglt stop +## postgrestools stop Stops the daemon server process. -**Usage**: **`pglt`** **`stop`** +**Usage**: **`postgrestools`** **`stop`** **Available options:** -- **`-h`**, **`--help`** — - Prints help information +- **`-h`**, **`--help`** — + Prints help information -## pglt init +## postgrestools init Bootstraps a new project. Creates a configuration file with some defaults. -**Usage**: **`pglt`** **`init`** +**Usage**: **`postgrestools`** **`init`** **Available options:** -- **`-h`**, **`--help`** — - Prints help information +- **`-h`**, **`--help`** — + Prints help information -## pglt lsp-proxy +## postgrestools lsp-proxy Acts as a server for the Language Server Protocol over stdin/stdout. -**Usage**: **`pglt`** **`lsp-proxy`** \[**`--config-path`**=_`PATH`_\] +**Usage**: **`postgrestools`** **`lsp-proxy`** \[**`--config-path`**=_`PATH`_\] **Available options:** -- **` --log-prefix-name`**=_`STRING`_ — + +- **` --log-prefix-name`**=_`STRING`_ — Allows to change the prefix applied to the file name of the logs. - Uses environment variable **`PGLT_LOG_PREFIX_NAME`** - [default: server.log] -- **` --log-path`**=_`PATH`_ — +- **` --log-path`**=_`PATH`_ — Allows to change the folder where logs are stored. - Uses environment variable **`PGLT_LOG_PATH`** -- **` --config-path`**=_`PATH`_ — - Allows to set a custom file path to the configuration file, or a custom directory path to find `pglt.jsonc` - +- **` --config-path`**=_`PATH`_ — + Allows to set a custom file path to the configuration file, or a custom directory path to find `postgrestools.jsonc` Uses environment variable **`PGLT_CONFIG_PATH`** -- **`-h`**, **`--help`** — +- **`-h`**, **`--help`** — Prints help information - -## pglt clean +## postgrestools clean Cleans the logs emitted by the daemon. -**Usage**: **`pglt`** **`clean`** +**Usage**: **`postgrestools`** **`clean`** **Available options:** -- **`-h`**, **`--help`** — - Prints help information - +- **`-h`**, **`--help`** — + Prints help information -[//]: # (END CLI_REF) +[//]: # "END CLI_REF" diff --git a/docs/codegen/Cargo.toml b/docs/codegen/Cargo.toml index ba1bc52f3..948574c57 100644 --- a/docs/codegen/Cargo.toml +++ b/docs/codegen/Cargo.toml @@ -22,7 +22,7 @@ pulldown-cmark = "0.12.2" pglt_configuration = { workspace = true, features = ["schema"] } pglt_flags = { workspace = true } -pglt_cli = { workspace = true } +pgt_cli = { workspace = true } pglt_analyse = { workspace = true } pglt_analyser = { workspace = true } pglt_diagnostics = { workspace = true } diff --git a/docs/codegen/src/cli_doc.rs b/docs/codegen/src/cli_doc.rs index ad299605d..cbde10282 100644 --- a/docs/codegen/src/cli_doc.rs +++ b/docs/codegen/src/cli_doc.rs @@ -1,4 +1,4 @@ -use pglt_cli::pglt_command; +use pgt_cli::pglt_command; use std::{fs, path::Path}; use crate::utils; diff --git a/packages/@postgrestools/backend-jsonrpc/src/workspace.ts b/packages/@postgrestools/backend-jsonrpc/src/workspace.ts index e71d94575..d7892f46a 100644 --- a/packages/@postgrestools/backend-jsonrpc/src/workspace.ts +++ b/packages/@postgrestools/backend-jsonrpc/src/workspace.ts @@ -423,28 +423,28 @@ export interface Workspace { export function createWorkspace(transport: Transport): Workspace { return { isPathIgnored(params) { - return transport.request("pgt/is_path_ignored", params); + return transport.request("pglt/is_path_ignored", params); }, getFileContent(params) { - return transport.request("pgt/get_file_content", params); + return transport.request("pglt/get_file_content", params); }, pullDiagnostics(params) { - return transport.request("pgt/pull_diagnostics", params); + return transport.request("pglt/pull_diagnostics", params); }, getCompletions(params) { - return transport.request("pgt/get_completions", params); + return transport.request("pglt/get_completions", params); }, updateSettings(params) { - return transport.request("pgt/update_settings", params); + return transport.request("pglt/update_settings", params); }, openFile(params) { - return transport.request("pgt/open_file", params); + return transport.request("pglt/open_file", params); }, changeFile(params) { - return transport.request("pgt/change_file", params); + return transport.request("pglt/change_file", params); }, closeFile(params) { - return transport.request("pgt/close_file", params); + return transport.request("pglt/close_file", params); }, destroy() { transport.destroy(); diff --git a/xtask/src/install.rs b/xtask/src/install.rs index 227170089..faaf5c56f 100644 --- a/xtask/src/install.rs +++ b/xtask/src/install.rs @@ -137,7 +137,7 @@ fn install_client(sh: &Shell, client_opt: ClientOpt) -> anyhow::Result<()> { } fn install_server(sh: &Shell) -> anyhow::Result<()> { - let cmd = cmd!(sh, "cargo install --path crates/pglt_cli --locked --force"); + let cmd = cmd!(sh, "cargo install --path crates/pgt_cli --locked --force"); cmd.run()?; Ok(()) }