diff --git a/Cargo.lock b/Cargo.lock index 6486b6d40..8844e46b5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -99,6 +99,22 @@ version = "1.0.94" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1fd03a028ef38ba2276dce7e33fcd6369c158a1bca17946c4b1b701891c1ff7" +[[package]] +name = "assert_cmd" +version = "2.0.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1835b7f27878de8525dc71410b5a31cdcc5f230aed5ba5df968e09c201b23d" +dependencies = [ + "anstyle", + "bstr", + "doc-comment", + "libc", + "predicates", + "predicates-core", + "predicates-tree", + "wait-timeout", +] + [[package]] name = "async-channel" version = "1.9.0" @@ -130,8 +146,8 @@ checksum = "30ca9a001c1e8ba5149f91a74362376cc6bc5b919d92d988668657bd570bdcec" dependencies = [ "async-task", "concurrent-queue", - "fastrand", - "futures-lite", + "fastrand 2.3.0", + "futures-lite 2.5.0", "slab", ] @@ -143,32 +159,61 @@ checksum = "05b1b633a2115cd122d73b955eadd9916c18c8f510ec9cd1686404c60ad1c29c" dependencies = [ "async-channel 2.3.1", "async-executor", - "async-io", - "async-lock", + "async-io 2.4.0", + "async-lock 3.4.0", "blocking", - "futures-lite", + "futures-lite 2.5.0", "once_cell", ] +[[package]] +name = "async-io" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fc5b45d93ef0529756f812ca52e44c221b35341892d3dcc34132ac02f3dd2af" +dependencies = [ + "async-lock 2.8.0", + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-lite 1.13.0", + "log", + "parking", + "polling 2.8.0", + "rustix 0.37.28", + "slab", + "socket2 0.4.10", + "waker-fn", +] + [[package]] name = "async-io" version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "43a2b323ccce0a1d90b449fd71f2a06ca7faa7c54c2751f06c9bd851fc061059" dependencies = [ - "async-lock", + "async-lock 3.4.0", "cfg-if", "concurrent-queue", "futures-io", - "futures-lite", + "futures-lite 2.5.0", "parking", - "polling", - "rustix", + "polling 3.7.4", + "rustix 0.38.42", "slab", "tracing", "windows-sys 0.59.0", ] +[[package]] +name = "async-lock" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "287272293e9d8c41773cec55e365490fe034813a2f172f502d6ddcf75b2f582b" +dependencies = [ + "event-listener 2.5.3", +] + [[package]] name = "async-lock" version = "3.4.0" @@ -188,13 +233,13 @@ checksum = "c634475f29802fde2b8f0b505b1bd00dfe4df7d4a000f0b36f7671197d5c3615" dependencies = [ "async-channel 1.9.0", "async-global-executor", - "async-io", - "async-lock", + "async-io 2.4.0", + "async-lock 3.4.0", "crossbeam-utils", "futures-channel", "futures-core", "futures-io", - "futures-lite", + "futures-lite 2.5.0", "gloo-timers", "kv-log-macro", "log", @@ -632,7 +677,7 @@ dependencies = [ "async-channel 2.3.1", "async-task", "futures-io", - "futures-lite", + "futures-lite 2.5.0", "piper", ] @@ -974,6 +1019,12 @@ dependencies = [ "powerfmt", ] +[[package]] +name = "difflib" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8" + [[package]] name = "digest" version = "0.10.7" @@ -1018,6 +1069,12 @@ dependencies = [ "syn 2.0.90", ] +[[package]] +name = "doc-comment" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fea41bba32d969b513997752735605054bc0dfa92b4c56bf1189f2e174be7a10" + [[package]] name = "docs_codegen" version = "0.0.0" @@ -1161,6 +1218,15 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "fastrand" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e51093e27b0797c359783294ca4f0a911c270184cb10f85783b118614a1501be" +dependencies = [ + "instant", +] + [[package]] name = "fastrand" version = "2.3.0" @@ -1183,6 +1249,15 @@ dependencies = [ "miniz_oxide", ] +[[package]] +name = "float-cmp" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b09cf3155332e944990140d967ff5eceb70df778b34f77d8075db46e4704e6d8" +dependencies = [ + "num-traits", +] + [[package]] name = "flume" version = "0.11.1" @@ -1268,13 +1343,28 @@ version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" +[[package]] +name = "futures-lite" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49a9d51ce47660b1e808d3c990b4709f2f415d928835a17dfd16991515c46bce" +dependencies = [ + "fastrand 1.9.0", + "futures-core", + "futures-io", + "memchr", + "parking", + "pin-project-lite", + "waker-fn", +] + [[package]] name = "futures-lite" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cef40d21ae2c515b51041df9ed313ed21e572df340ea58a922a0aefe7e8891a1" dependencies = [ - "fastrand", + "fastrand 2.3.0", "futures-core", "futures-io", "parking", @@ -1453,6 +1543,12 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hermit-abi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" + [[package]] name = "hermit-abi" version = "0.4.0" @@ -1688,6 +1784,26 @@ dependencies = [ "similar", ] +[[package]] +name = "instant" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "io-lifetimes" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eae7b9aee968036d54dce06cebaefd919e4472e753296daccd6d344e3e2df0c2" +dependencies = [ + "hermit-abi 0.3.9", + "libc", + "windows-sys 0.48.0", +] + [[package]] name = "is_ci" version = "1.2.0" @@ -1817,6 +1933,12 @@ version = "0.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" +[[package]] +name = "linux-raw-sys" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef53942eb7bf7ff43a617b3e2c1c4a5ecf5944a7c1bc12d7ee39bbb15e5c1519" + [[package]] name = "linux-raw-sys" version = "0.4.14" @@ -1955,6 +2077,12 @@ dependencies = [ "minimal-lexical", ] +[[package]] +name = "normalize-line-endings" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be" + [[package]] name = "ntest" version = "0.9.3" @@ -2251,6 +2379,7 @@ name = "pgt_cli" version = "0.0.0" dependencies = [ "anyhow", + "assert_cmd", "biome_deserialize 0.6.0", "biome_deserialize_macros 0.6.0", "bpaf", @@ -2269,6 +2398,7 @@ dependencies = [ "pgt_lsp", "pgt_text_edit", "pgt_workspace", + "predicates", "quick-junit", "rayon", "rustc-hash 2.1.0", @@ -2683,7 +2813,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96c8c490f422ef9a4efd2cb5b42b76c8613d7e7dfc1caf667b8a3350a5acc066" dependencies = [ "atomic-waker", - "fastrand", + "fastrand 2.3.0", "futures-io", ] @@ -2714,6 +2844,22 @@ version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "953ec861398dccce10c670dfeaf3ec4911ca479e9c02154b3a215178c5f566f2" +[[package]] +name = "polling" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b2d323e8ca7996b3e23126511a523f7e62924d93ecd5ae73b333815b0eb3dce" +dependencies = [ + "autocfg", + "bitflags 1.3.2", + "cfg-if", + "concurrent-queue", + "libc", + "log", + "pin-project-lite", + "windows-sys 0.48.0", +] + [[package]] name = "polling" version = "3.7.4" @@ -2722,9 +2868,9 @@ checksum = "a604568c3202727d1507653cb121dbd627a58684eb09a820fd746bee38b4442f" dependencies = [ "cfg-if", "concurrent-queue", - "hermit-abi", + "hermit-abi 0.4.0", "pin-project-lite", - "rustix", + "rustix 0.38.42", "tracing", "windows-sys 0.59.0", ] @@ -2744,6 +2890,36 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "predicates" +version = "3.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5d19ee57562043d37e82899fade9a22ebab7be9cef5026b07fda9cdd4293573" +dependencies = [ + "anstyle", + "difflib", + "float-cmp", + "normalize-line-endings", + "predicates-core", + "regex", +] + +[[package]] +name = "predicates-core" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "727e462b119fe9c93fd0eb1429a5f7647394014cf3c04ab2c0350eeb09095ffa" + +[[package]] +name = "predicates-tree" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72dd2d6d381dfb73a193c7fca536518d7caee39fc8503f74e7dc0be0531b425c" +dependencies = [ + "predicates-core", + "termtree", +] + [[package]] name = "prettyplease" version = "0.2.25" @@ -3106,6 +3282,20 @@ version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c7fb8039b3032c191086b10f11f319a6e99e1e82889c5cc6046f515c9db1d497" +[[package]] +name = "rustix" +version = "0.37.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "519165d378b97752ca44bbe15047d5d3409e875f39327546b42ac81d7e18c1b6" +dependencies = [ + "bitflags 1.3.2", + "errno", + "io-lifetimes", + "libc", + "linux-raw-sys 0.3.8", + "windows-sys 0.48.0", +] + [[package]] name = "rustix" version = "0.38.42" @@ -3115,7 +3305,7 @@ dependencies = [ "bitflags 2.6.0", "errno", "libc", - "linux-raw-sys", + "linux-raw-sys 0.4.14", "windows-sys 0.59.0", ] @@ -3342,6 +3532,16 @@ dependencies = [ "serde", ] +[[package]] +name = "socket2" +version = "0.4.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7916fc008ca5542385b89a3d3ce689953c143e9304a9bf8beec1de48994c0d" +dependencies = [ + "libc", + "winapi", +] + [[package]] name = "socket2" version = "0.5.8" @@ -3400,6 +3600,8 @@ version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d4d8060b456358185f7d50c55d9b5066ad956956fddec42ee2e8567134a8936e" dependencies = [ + "async-io 1.13.0", + "async-std", "atoi", "byteorder", "bytes", @@ -3452,6 +3654,7 @@ version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1804e8a7c7865599c9c79be146dc8a9fd8cc86935fa641d3ea58e5f0688abaa5" dependencies = [ + "async-std", "dotenvy", "either", "heck 0.5.0", @@ -3674,10 +3877,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a8a559c81686f576e8cd0290cd2a24a2a9ad80c98b3478856500fcbd7acd704" dependencies = [ "cfg-if", - "fastrand", + "fastrand 2.3.0", "getrandom", "once_cell", - "rustix", + "rustix 0.38.42", "windows-sys 0.59.0", ] @@ -3690,6 +3893,12 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "termtree" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" + [[package]] name = "thiserror" version = "1.0.69" @@ -3829,7 +4038,7 @@ dependencies = [ "parking_lot", "pin-project-lite", "signal-hook-registry", - "socket2", + "socket2 0.5.8", "tokio-macros", "windows-sys 0.52.0", ] @@ -4243,6 +4452,21 @@ dependencies = [ "quote", ] +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + +[[package]] +name = "waker-fn" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "317211a0dc0ceedd78fb2ca9a44aed3d7b9b26f81870d485c07122b4350673b7" + [[package]] name = "walkdir" version = "2.5.0" @@ -4351,7 +4575,7 @@ dependencies = [ "either", "home", "once_cell", - "rustix", + "rustix 0.38.42", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index d69d16fbb..c37231ac2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,16 +39,17 @@ serde = "1.0.195" serde_json = "1.0.114" similar = "2.6.0" smallvec = { version = "1.13.2", features = ["union", "const_new", "serde"] } -sqlx = { version = "0.8.2", features = ["runtime-tokio", "postgres", "json"] } -syn = "1.0.109" -termcolor = "1.4.1" -tokio = { version = "1.40.0", features = ["full"] } -tower-lsp = "0.20.0" -tracing = { version = "0.1.40", default-features = false, features = ["std"] } -tracing-subscriber = "0.3.18" -tree-sitter = "0.20.10" -tree_sitter_sql = { path = "./lib/tree_sitter_sql", version = "0.0.0" } -unicode-width = "0.1.12" +# this will use tokio if available, otherwise async-std +sqlx = { version = "0.8.2", features = ["runtime-tokio", "runtime-async-std", "postgres", "json"] } +syn = "1.0.109" +termcolor = "1.4.1" +tokio = { version = "1.40.0", features = ["full"] } +tower-lsp = "0.20.0" +tracing = { version = "0.1.40", default-features = false, features = ["std"] } +tracing-subscriber = "0.3.18" +tree-sitter = "0.20.10" +tree_sitter_sql = { path = "./lib/tree_sitter_sql", version = "0.0.0" } +unicode-width = "0.1.12" # postgres specific crates pgt_analyse = { path = "./crates/pgt_analyse", version = "0.0.0" } diff --git a/crates/pgt_analyse/src/categories.rs b/crates/pgt_analyse/src/categories.rs index ae4c65e15..e5dd51c2b 100644 --- a/crates/pgt_analyse/src/categories.rs +++ b/crates/pgt_analyse/src/categories.rs @@ -70,34 +70,34 @@ impl ActionCategory { match self { ActionCategory::QuickFix(tag) => { if tag.is_empty() { - Cow::Borrowed("quickfix.pglt") + Cow::Borrowed("quickfix.pgt") } else { - Cow::Owned(format!("quickfix.pglt.{tag}")) + Cow::Owned(format!("quickfix.pgt.{tag}")) } } - ActionCategory::Refactor(RefactorKind::None) => Cow::Borrowed("refactor.pglt"), + ActionCategory::Refactor(RefactorKind::None) => Cow::Borrowed("refactor.pgt"), ActionCategory::Refactor(RefactorKind::Extract) => { - Cow::Borrowed("refactor.extract.pglt") + Cow::Borrowed("refactor.extract.pgt") } - ActionCategory::Refactor(RefactorKind::Inline) => Cow::Borrowed("refactor.inline.pglt"), + ActionCategory::Refactor(RefactorKind::Inline) => Cow::Borrowed("refactor.inline.pgt"), ActionCategory::Refactor(RefactorKind::Rewrite) => { - Cow::Borrowed("refactor.rewrite.pglt") + Cow::Borrowed("refactor.rewrite.pgt") } ActionCategory::Refactor(RefactorKind::Other(tag)) => { - Cow::Owned(format!("refactor.{tag}.pglt")) + Cow::Owned(format!("refactor.{tag}.pgt")) } - ActionCategory::Source(SourceActionKind::None) => Cow::Borrowed("source.pglt"), - ActionCategory::Source(SourceActionKind::FixAll) => Cow::Borrowed("source.fixAll.pglt"), + ActionCategory::Source(SourceActionKind::None) => Cow::Borrowed("source.pgt"), + ActionCategory::Source(SourceActionKind::FixAll) => Cow::Borrowed("source.fixAll.pgt"), ActionCategory::Source(SourceActionKind::OrganizeImports) => { - Cow::Borrowed("source.organizeImports.pglt") + Cow::Borrowed("source.organizeImports.pgt") } ActionCategory::Source(SourceActionKind::Other(tag)) => { - Cow::Owned(format!("source.{tag}.pglt")) + Cow::Owned(format!("source.{tag}.pgt")) } - ActionCategory::Other(tag) => Cow::Owned(format!("{tag}.pglt")), + ActionCategory::Other(tag) => Cow::Owned(format!("{tag}.pgt")), } } } diff --git a/crates/pgt_cli/Cargo.toml b/crates/pgt_cli/Cargo.toml index 16594a06c..ca61cf653 100644 --- a/crates/pgt_cli/Cargo.toml +++ b/crates/pgt_cli/Cargo.toml @@ -51,6 +51,8 @@ mimalloc = "0.1.43" tikv-jemallocator = "0.6.0" [dev-dependencies] +assert_cmd = "2.0.16" +predicates = "3.1.3" [lib] doctest = false diff --git a/crates/pgt_cli/src/cli_options.rs b/crates/pgt_cli/src/cli_options.rs index 9b1c36507..b795c65f6 100644 --- a/crates/pgt_cli/src/cli_options.rs +++ b/crates/pgt_cli/src/cli_options.rs @@ -48,7 +48,7 @@ pub struct CliOptions { #[bpaf(long("no-errors-on-unmatched"), switch)] pub no_errors_on_unmatched: bool, - /// Tell PgLT to exit with an error code if some diagnostics emit warnings. + /// Tell Postgres Tools to exit with an error code if some diagnostics emit warnings. #[bpaf(long("error-on-warnings"), switch)] pub error_on_warnings: bool, @@ -86,7 +86,7 @@ pub struct CliOptions { fallback(Severity::default()), display_fallback )] - /// 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. + /// The level of diagnostics to show. In order, from the lowest to the most important: info, warn, error. Passing `--diagnostic-level=error` will cause Postgres Tools to print only diagnostics that contain only errors. pub diagnostic_level: Severity, } diff --git a/crates/pgt_cli/src/commands/daemon.rs b/crates/pgt_cli/src/commands/daemon.rs index 17d6e58ba..db6c4eb16 100644 --- a/crates/pgt_cli/src/commands/daemon.rs +++ b/crates/pgt_cli/src/commands/daemon.rs @@ -206,10 +206,10 @@ pub(crate) fn read_most_recent_log_file( /// The events received by the subscriber are filtered at the `info` level, /// then printed using the [HierarchicalLayer] layer, and the resulting text /// is written to log files rotated on a hourly basis (in -/// `pglt-logs/server.log.yyyy-MM-dd-HH` files inside the system temporary +/// `pgt-logs/server.log.yyyy-MM-dd-HH` files inside the system temporary /// directory) fn setup_tracing_subscriber(log_path: Option, log_file_name_prefix: Option) { - let pgt_log_path = log_path.unwrap_or(pgt_fs::ensure_cache_dir().join("pglt-logs")); + let pgt_log_path = log_path.unwrap_or(pgt_fs::ensure_cache_dir().join("pgt-logs")); let appender_builder = tracing_appender::rolling::RollingFileAppender::builder(); let file_appender = appender_builder .filename_prefix(log_file_name_prefix.unwrap_or(String::from("server.log"))) @@ -235,16 +235,16 @@ fn setup_tracing_subscriber(log_path: Option, log_file_name_prefix: Opt pub fn default_pgt_log_path() -> PathBuf { match env::var_os("PGT_LOG_PATH") { Some(directory) => PathBuf::from(directory), - None => pgt_fs::ensure_cache_dir().join("pglt-logs"), + None => pgt_fs::ensure_cache_dir().join("pgt-logs"), } } /// Tracing filter enabling: /// - All spans and events at level info or higher -/// - All spans and events at level debug in crates whose name starts with `pglt` +/// - All spans and events at level debug in crates whose name starts with `pgt` struct LoggingFilter; -/// Tracing filter used for spans emitted by `pglt*` crates +/// Tracing filter used for spans emitted by `pgt*` crates const SELF_FILTER: LevelFilter = if cfg!(debug_assertions) { LevelFilter::TRACE } else { @@ -253,7 +253,7 @@ const SELF_FILTER: LevelFilter = if cfg!(debug_assertions) { impl LoggingFilter { fn is_enabled(&self, meta: &Metadata<'_>) -> bool { - let filter = if meta.target().starts_with("pglt") { + let filter = if meta.target().starts_with("pgt") { SELF_FILTER } else { LevelFilter::INFO diff --git a/crates/pgt_cli/src/commands/mod.rs b/crates/pgt_cli/src/commands/mod.rs index 63e509d16..b475d2980 100644 --- a/crates/pgt_cli/src/commands/mod.rs +++ b/crates/pgt_cli/src/commands/mod.rs @@ -24,7 +24,7 @@ pub(crate) mod version; #[derive(Debug, Clone, Bpaf)] #[bpaf(options, version(VERSION))] -/// PgLT official CLI. Use it to check the health of your project or run it to check single files. +/// Postgres Tools official CLI. Use it to check the health of your project or run it to check single files. pub enum PgtCommand { /// Shows the version information and quit. #[bpaf(command)] @@ -87,7 +87,7 @@ pub enum PgtCommand { long("log-path"), argument("PATH"), hide_usage, - fallback(pgt_fs::ensure_cache_dir().join("pglt-logs")), + fallback(pgt_fs::ensure_cache_dir().join("pgt-logs")), )] log_path: PathBuf, /// Allows to set a custom file path to the configuration file, @@ -123,7 +123,7 @@ pub enum PgtCommand { long("log-path"), argument("PATH"), hide_usage, - fallback(pgt_fs::ensure_cache_dir().join("pglt-logs")), + fallback(pgt_fs::ensure_cache_dir().join("pgt-logs")), )] log_path: PathBuf, /// Allows to set a custom file path to the configuration file, @@ -157,7 +157,7 @@ pub enum PgtCommand { long("log-path"), argument("PATH"), hide_usage, - fallback(pgt_fs::ensure_cache_dir().join("pglt-logs")), + fallback(pgt_fs::ensure_cache_dir().join("pgt-logs")), )] log_path: PathBuf, @@ -197,7 +197,7 @@ impl PgtCommand { } // We want force colors in CI, to give e better UX experience // Unless users explicitly set the colors flag - // if matches!(self, PgLTCommand::Ci { .. }) && cli_options.colors.is_none() { + // if matches!(self, Postgres ToolsCommand::Ci { .. }) && cli_options.colors.is_none() { // return Some(&ColorsArg::Force); // } // Normal behaviors diff --git a/crates/pgt_cli/src/diagnostics.rs b/crates/pgt_cli/src/diagnostics.rs index acee31eeb..0c5bd24f9 100644 --- a/crates/pgt_cli/src/diagnostics.rs +++ b/crates/pgt_cli/src/diagnostics.rs @@ -12,10 +12,10 @@ fn command_name() -> String { current_exe() .ok() .and_then(|path| Some(path.file_name()?.to_str()?.to_string())) - .unwrap_or_else(|| String::from("pglt")) + .unwrap_or_else(|| String::from("postgrestools")) } -/// A diagnostic that is emitted when running PgLT via CLI. +/// A diagnostic that is emitted when running Postgres Tools via CLI. /// /// When displaying the diagnostic, #[derive(Debug, Diagnostic)] diff --git a/crates/pgt_cli/src/execute/mod.rs b/crates/pgt_cli/src/execute/mod.rs index 9e1420117..753e739d3 100644 --- a/crates/pgt_cli/src/execute/mod.rs +++ b/crates/pgt_cli/src/execute/mod.rs @@ -11,7 +11,7 @@ use crate::reporter::junit::{JunitReporter, JunitReporterVisitor}; use crate::reporter::terminal::{ConsoleReporter, ConsoleReporterVisitor}; use crate::{CliDiagnostic, CliSession, DiagnosticsPayload, Reporter}; use pgt_diagnostics::{Category, category}; -use pgt_fs::PgLTPath; +use pgt_fs::PgTPath; use std::borrow::Borrow; use std::ffi::OsString; use std::fmt::{Display, Formatter}; @@ -232,7 +232,7 @@ pub fn execute_mode( // don't do any traversal if there's some content coming from stdin if let Some(stdin) = execution.as_stdin_file() { - let pgt_path = PgLTPath::new(stdin.as_path()); + let pgt_path = PgTPath::new(stdin.as_path()); std_in::run( session, &execution, diff --git a/crates/pgt_cli/src/execute/process_file.rs b/crates/pgt_cli/src/execute/process_file.rs index ab430d84b..f2d4d19e6 100644 --- a/crates/pgt_cli/src/execute/process_file.rs +++ b/crates/pgt_cli/src/execute/process_file.rs @@ -5,7 +5,7 @@ use crate::execute::TraversalMode; use crate::execute::traverse::TraversalOptions; use check::check_file; use pgt_diagnostics::Error; -use pgt_fs::PgLTPath; +use pgt_fs::PgTPath; use std::marker::PhantomData; use std::ops::Deref; @@ -111,7 +111,7 @@ impl<'ctx, 'app> Deref for SharedTraversalOptions<'ctx, 'app> { /// diagnostics were emitted, or compare the formatted code with the original /// content of the file and emit a diff or write the new content to the disk if /// write mode is enabled -pub(crate) fn process_file(ctx: &TraversalOptions, pgt_path: &PgLTPath) -> FileResult { +pub(crate) fn process_file(ctx: &TraversalOptions, pgt_path: &PgTPath) -> FileResult { tracing::trace_span!("process_file", path = ?pgt_path).in_scope(move || { let shared_context = &SharedTraversalOptions::new(ctx); diff --git a/crates/pgt_cli/src/execute/process_file/workspace_file.rs b/crates/pgt_cli/src/execute/process_file/workspace_file.rs index 36c4f7a4b..55f36aad3 100644 --- a/crates/pgt_cli/src/execute/process_file/workspace_file.rs +++ b/crates/pgt_cli/src/execute/process_file/workspace_file.rs @@ -1,7 +1,7 @@ use crate::execute::diagnostics::{ResultExt, ResultIoExt}; use crate::execute::process_file::SharedTraversalOptions; use pgt_diagnostics::{Error, category}; -use pgt_fs::{File, OpenOptions, PgLTPath}; +use pgt_fs::{File, OpenOptions, PgTPath}; use pgt_workspace::workspace::{ChangeParams, FileGuard, OpenFileParams}; use pgt_workspace::{Workspace, WorkspaceError}; use std::ffi::OsStr; @@ -21,7 +21,7 @@ impl<'ctx, 'app> WorkspaceFile<'ctx, 'app> { ctx: &SharedTraversalOptions<'ctx, 'app>, path: &Path, ) -> Result { - let pgt_path = PgLTPath::new(path); + let pgt_path = PgTPath::new(path); let open_options = OpenOptions::default() .read(true) .write(ctx.execution.requires_write_access()); diff --git a/crates/pgt_cli/src/execute/std_in.rs b/crates/pgt_cli/src/execute/std_in.rs index 9652e778c..8fee336f0 100644 --- a/crates/pgt_cli/src/execute/std_in.rs +++ b/crates/pgt_cli/src/execute/std_in.rs @@ -3,12 +3,12 @@ use crate::execute::Execution; use crate::{CliDiagnostic, CliSession}; use pgt_console::{ConsoleExt, markup}; -use pgt_fs::PgLTPath; +use pgt_fs::PgTPath; pub(crate) fn run<'a>( session: CliSession, mode: &'a Execution, - pgt_path: PgLTPath, + pgt_path: PgTPath, content: &'a str, verbose: bool, ) -> Result<(), CliDiagnostic> { diff --git a/crates/pgt_cli/src/execute/traverse.rs b/crates/pgt_cli/src/execute/traverse.rs index 427b06a55..700aa4c95 100644 --- a/crates/pgt_cli/src/execute/traverse.rs +++ b/crates/pgt_cli/src/execute/traverse.rs @@ -7,7 +7,7 @@ use crate::{CliDiagnostic, CliSession}; use crossbeam::channel::{Receiver, Sender, unbounded}; use pgt_diagnostics::DiagnosticTags; use pgt_diagnostics::{DiagnosticExt, Error, Resource, Severity}; -use pgt_fs::{FileSystem, PathInterner, PgLTPath}; +use pgt_fs::{FileSystem, PathInterner, PgTPath}; use pgt_fs::{TraversalContext, TraversalScope}; use pgt_workspace::dome::Dome; use pgt_workspace::workspace::IsPathIgnoredParams; @@ -31,7 +31,7 @@ use std::{ pub(crate) struct TraverseResult { pub(crate) summary: TraversalSummary, - pub(crate) evaluated_paths: BTreeSet, + pub(crate) evaluated_paths: BTreeSet, pub(crate) diagnostics: Vec, } @@ -86,7 +86,7 @@ pub(crate) fn traverse( let (duration, evaluated_paths, diagnostics) = thread::scope(|s| { let handler = thread::Builder::new() - .name(String::from("pglt::console")) + .name(String::from("pgt::console")) .spawn_scoped(s, || printer.run(receiver, recv_files)) .expect("failed to spawn console thread"); @@ -148,7 +148,7 @@ fn init_thread_pool() { static INIT_ONCE: Once = Once::new(); INIT_ONCE.call_once(|| { rayon::ThreadPoolBuilder::new() - .thread_name(|index| format!("pglt::worker_{index}")) + .thread_name(|index| format!("pgt::worker_{index}")) .build_global() .expect("failed to initialize the global thread pool"); }); @@ -160,7 +160,7 @@ fn traverse_inputs( fs: &dyn FileSystem, inputs: Vec, ctx: &TraversalOptions, -) -> (Duration, BTreeSet) { +) -> (Duration, BTreeSet) { let start = Instant::now(); fs.traversal(Box::new(move |scope: &dyn TraversalScope| { for input in inputs { @@ -412,11 +412,11 @@ pub(crate) struct TraversalOptions<'ctx, 'app> { pub(crate) remaining_diagnostics: &'ctx AtomicU32, /// List of paths that should be processed - pub(crate) evaluated_paths: RwLock>, + pub(crate) evaluated_paths: RwLock>, } impl TraversalOptions<'_, '_> { - pub(crate) fn increment_changed(&self, path: &PgLTPath) { + pub(crate) fn increment_changed(&self, path: &PgTPath) { self.changed.fetch_add(1, Ordering::Relaxed); self.evaluated_paths .write() @@ -436,7 +436,7 @@ impl TraversalOptions<'_, '_> { self.messages.send(msg.into()).ok(); } - pub(crate) fn protected_file(&self, pgt_path: &PgLTPath) { + pub(crate) fn protected_file(&self, pgt_path: &PgTPath) { self.push_diagnostic(WorkspaceError::protected_file(pgt_path.display().to_string()).into()) } } @@ -446,7 +446,7 @@ impl TraversalContext for TraversalOptions<'_, '_> { &self.interner } - fn evaluated_paths(&self) -> BTreeSet { + fn evaluated_paths(&self) -> BTreeSet { self.evaluated_paths.read().unwrap().clone() } @@ -454,7 +454,7 @@ impl TraversalContext for TraversalOptions<'_, '_> { self.push_message(error); } - fn can_handle(&self, pgt_path: &PgLTPath) -> bool { + fn can_handle(&self, pgt_path: &PgTPath) -> bool { let path = pgt_path.as_path(); let is_valid_file = self.fs.path_is_file(path) @@ -492,22 +492,22 @@ impl TraversalContext for TraversalOptions<'_, '_> { } } - fn handle_path(&self, path: PgLTPath) { + fn handle_path(&self, path: PgTPath) { handle_file(self, &path) } - fn store_path(&self, path: PgLTPath) { + fn store_path(&self, path: PgTPath) { self.evaluated_paths .write() .unwrap() - .insert(PgLTPath::new(path.as_path())); + .insert(PgTPath::new(path.as_path())); } } /// This function wraps the [process_file] function implementing the traversal /// in a [catch_unwind] block and emit diagnostics in case of error (either the /// traversal function returns Err or panics) -fn handle_file(ctx: &TraversalOptions, path: &PgLTPath) { +fn handle_file(ctx: &TraversalOptions, path: &PgTPath) { match catch_unwind(move || process_file(ctx, path)) { Ok(Ok(FileStatus::Changed)) => { ctx.increment_changed(path); diff --git a/crates/pgt_cli/src/logging.rs b/crates/pgt_cli/src/logging.rs index 05a7b970a..e90866558 100644 --- a/crates/pgt_cli/src/logging.rs +++ b/crates/pgt_cli/src/logging.rs @@ -91,12 +91,12 @@ impl Display for LoggingLevel { /// Tracing filter enabling: /// - All spans and events at level info or higher -/// - All spans and events at level debug in crates whose name starts with `pglt` +/// - All spans and events at level debug in crates whose name starts with `pgt` struct LoggingFilter { level: LoggingLevel, } -/// Tracing filter used for spans emitted by `pglt*` crates +/// Tracing filter used for spans emitted by `pgt*` crates const SELF_FILTER: LevelFilter = if cfg!(debug_assertions) { LevelFilter::TRACE } else { @@ -105,7 +105,7 @@ const SELF_FILTER: LevelFilter = if cfg!(debug_assertions) { impl LoggingFilter { fn is_enabled(&self, meta: &Metadata<'_>) -> bool { - let filter = if meta.target().starts_with("pglt") { + let filter = if meta.target().starts_with("pgt") { if let Some(level) = self.level.to_filter_level() { level } else { diff --git a/crates/pgt_cli/src/panic.rs b/crates/pgt_cli/src/panic.rs index bfaacd418..5b8cb16d3 100644 --- a/crates/pgt_cli/src/panic.rs +++ b/crates/pgt_cli/src/panic.rs @@ -19,7 +19,7 @@ fn panic_handler(info: &PanicHookInfo) { writeln!(error, "Encountered an unexpected error").unwrap(); writeln!(error).unwrap(); - writeln!(error, "This is a bug in PgLT, not an error in your code, and we would appreciate it if you could report it along with the following information to help us fixing the issue:").unwrap(); + writeln!(error, "This is a bug in Postgres Tools, not an error in your code, and we would appreciate it if you could report it along with the following information to help us fixing the issue:").unwrap(); writeln!(error).unwrap(); if let Some(location) = info.location() { diff --git a/crates/pgt_cli/src/reporter/junit.rs b/crates/pgt_cli/src/reporter/junit.rs index a1a42d513..670bf8d40 100644 --- a/crates/pgt_cli/src/reporter/junit.rs +++ b/crates/pgt_cli/src/reporter/junit.rs @@ -34,7 +34,7 @@ pub(crate) struct JunitReporterVisitor<'a>(pub(crate) Report, pub(crate) &'a mut impl<'a> JunitReporterVisitor<'a> { pub(crate) fn new(console: &'a mut dyn Console) -> Self { - let report = Report::new("PgLT"); + let report = Report::new("PostgresTools"); Self(report, console) } } @@ -85,7 +85,7 @@ impl ReporterVisitor for JunitReporterVisitor<'_> { )); let mut case = TestCase::new( format!( - "org.pglt.{}", + "org.pgt.{}", diagnostic .category() .map(|c| c.name()) @@ -103,7 +103,7 @@ impl ReporterVisitor for JunitReporterVisitor<'_> { "column".into(), start.column_number.get().to_string().into(), ); - test_suite.extra.insert("package".into(), "org.pglt".into()); + test_suite.extra.insert("package".into(), "org.pgt".into()); test_suite.add_test_case(case); self.0.add_test_suite(test_suite); } diff --git a/crates/pgt_cli/src/reporter/mod.rs b/crates/pgt_cli/src/reporter/mod.rs index 0a95f663d..ed265f9b0 100644 --- a/crates/pgt_cli/src/reporter/mod.rs +++ b/crates/pgt_cli/src/reporter/mod.rs @@ -5,7 +5,7 @@ pub(crate) mod terminal; use crate::execute::Execution; use pgt_diagnostics::{Error, Severity}; -use pgt_fs::PgLTPath; +use pgt_fs::PgTPath; use serde::Serialize; use std::collections::BTreeSet; use std::io; @@ -49,7 +49,7 @@ pub trait ReporterVisitor { ) -> io::Result<()>; /// Writes the paths that were handled during a run. - fn report_handled_paths(&mut self, evaluated_paths: BTreeSet) -> io::Result<()> { + fn report_handled_paths(&mut self, evaluated_paths: BTreeSet) -> io::Result<()> { let _ = evaluated_paths; Ok(()) } diff --git a/crates/pgt_cli/src/reporter/terminal.rs b/crates/pgt_cli/src/reporter/terminal.rs index 36f06b519..b33967867 100644 --- a/crates/pgt_cli/src/reporter/terminal.rs +++ b/crates/pgt_cli/src/reporter/terminal.rs @@ -5,7 +5,7 @@ use pgt_console::fmt::Formatter; use pgt_console::{Console, ConsoleExt, fmt, markup}; use pgt_diagnostics::advice::ListAdvice; use pgt_diagnostics::{Diagnostic, PrintDiagnostic}; -use pgt_fs::PgLTPath; +use pgt_fs::PgTPath; use std::collections::BTreeSet; use std::io; use std::time::Duration; @@ -14,7 +14,7 @@ pub(crate) struct ConsoleReporter { pub(crate) summary: TraversalSummary, pub(crate) diagnostics_payload: DiagnosticsPayload, pub(crate) execution: Execution, - pub(crate) evaluated_paths: BTreeSet, + pub(crate) evaluated_paths: BTreeSet, } impl Reporter for ConsoleReporter { @@ -66,7 +66,7 @@ impl ReporterVisitor for ConsoleReporterVisitor<'_> { Ok(()) } - fn report_handled_paths(&mut self, evaluated_paths: BTreeSet) -> io::Result<()> { + fn report_handled_paths(&mut self, evaluated_paths: BTreeSet) -> io::Result<()> { let evaluated_paths_diagnostic = EvaluatedPathsDiagnostic { advice: ListAdvice { list: evaluated_paths diff --git a/crates/pgt_cli/src/service/mod.rs b/crates/pgt_cli/src/service/mod.rs index 314e50f98..1be4ea5cd 100644 --- a/crates/pgt_cli/src/service/mod.rs +++ b/crates/pgt_cli/src/service/mod.rs @@ -191,7 +191,7 @@ impl WorkspaceTransport for SocketTransport { self.pending_requests.insert(request.id, send); - let is_shutdown = request.method == "pglt/shutdown"; + let is_shutdown = request.method == "pgt/shutdown"; let request = JsonRpcRequest { jsonrpc: Cow::Borrowed("2.0"), diff --git a/crates/pgt_cli/src/service/unix.rs b/crates/pgt_cli/src/service/unix.rs index 29227acc7..68322584a 100644 --- a/crates/pgt_cli/src/service/unix.rs +++ b/crates/pgt_cli/src/service/unix.rs @@ -21,7 +21,7 @@ use tracing::{Instrument, debug, info}; /// Returns the filesystem path of the global socket used to communicate with /// the server daemon fn get_socket_name() -> PathBuf { - pgt_fs::ensure_cache_dir().join(format!("pglt-socket-{}", pgt_configuration::VERSION)) + pgt_fs::ensure_cache_dir().join(format!("pgt-socket-{}", pgt_configuration::VERSION)) } pub(crate) fn enumerate_pipes() -> io::Result> { @@ -31,7 +31,7 @@ pub(crate) fn enumerate_pipes() -> io::Result> { let file_name = entry.file_name()?; let file_name = file_name.to_str()?; - let version = file_name.strip_prefix("pglt-socket")?; + let version = file_name.strip_prefix("pgt-socket")?; if version.is_empty() { Some(String::new()) } else { diff --git a/crates/pgt_cli/src/service/windows.rs b/crates/pgt_cli/src/service/windows.rs index dd81a10b2..8cdc7edc1 100644 --- a/crates/pgt_cli/src/service/windows.rs +++ b/crates/pgt_cli/src/service/windows.rs @@ -24,7 +24,7 @@ use tracing::Instrument; /// Returns the name of the global named pipe used to communicate with the /// server daemon fn get_pipe_name() -> String { - format!(r"\\.\pipe\pglt-service-{}", pgt_configuration::VERSION) + format!(r"\\.\pipe\pgt-service-{}", pgt_configuration::VERSION) } pub(crate) fn enumerate_pipes() -> io::Result> { @@ -34,7 +34,7 @@ pub(crate) fn enumerate_pipes() -> io::Result> { let file_name = entry.file_name()?; let file_name = file_name.to_str()?; - let version = file_name.strip_prefix("pglt-service")?; + let version = file_name.strip_prefix("pgt-service")?; if version.is_empty() { Some(String::new()) } else { diff --git a/crates/pgt_cli/tests/assert_cmd.rs b/crates/pgt_cli/tests/assert_cmd.rs new file mode 100644 index 000000000..a7ddc17fb --- /dev/null +++ b/crates/pgt_cli/tests/assert_cmd.rs @@ -0,0 +1,16 @@ +use std::path::PathBuf; + +use assert_cmd::Command; +use predicates::prelude::*; + +#[test] +fn test_cli_check_command() { + let mut cmd = Command::cargo_bin("postgrestools").unwrap(); + + let test_sql_path = PathBuf::from("tests/fixtures/test.sql"); + + cmd.args(["check", test_sql_path.to_str().unwrap()]) + .assert() + .failure() + .stdout(predicate::str::contains("Found 1 error")); +} diff --git a/crates/pgt_cli/tests/commands/check.rs b/crates/pgt_cli/tests/commands/check.rs new file mode 100644 index 000000000..ce0de03da --- /dev/null +++ b/crates/pgt_cli/tests/commands/check.rs @@ -0,0 +1,24 @@ +use bpaf::Args; +use std::path::Path; + +use crate::run_cli; +use pgt_console::BufferConsole; +use pgt_fs::MemoryFileSystem; +use pgt_workspace::DynRef; + +#[test] +fn syntax_error() { + let mut fs = MemoryFileSystem::default(); + let mut console = BufferConsole::default(); + + let file_path = Path::new("test.sql"); + fs.insert(file_path.into(), "select 1".as_bytes()); + + let result = run_cli( + DynRef::Borrowed(&mut fs), + &mut console, + Args::from([("check"), file_path.as_os_str().to_str().unwrap()].as_slice()), + ); + + assert!(result.is_ok(), "run_cli returned {result:?}"); +} diff --git a/crates/pgt_cli/tests/commands/mod.rs b/crates/pgt_cli/tests/commands/mod.rs new file mode 100644 index 000000000..be0c6a3ea --- /dev/null +++ b/crates/pgt_cli/tests/commands/mod.rs @@ -0,0 +1 @@ +mod check; diff --git a/crates/pgt_cli/tests/fixtures/test.sql b/crates/pgt_cli/tests/fixtures/test.sql new file mode 100644 index 000000000..de3b52a5e --- /dev/null +++ b/crates/pgt_cli/tests/fixtures/test.sql @@ -0,0 +1,2 @@ +alter tqjable test drop column id; + diff --git a/crates/pgt_cli/tests/main.rs b/crates/pgt_cli/tests/main.rs new file mode 100644 index 000000000..4ab061727 --- /dev/null +++ b/crates/pgt_cli/tests/main.rs @@ -0,0 +1,53 @@ +mod commands; + +use bpaf::ParseFailure; +use pgt_cli::{CliDiagnostic, CliSession, pgt_command}; +use pgt_console::{Console, ConsoleExt, markup}; +use pgt_fs::FileSystem; +use pgt_workspace::{App, DynRef}; + +/// Create an [App] instance using the provided [FileSystem] and [Console] +/// instance, and using an in-process "remote" instance of the workspace +pub(crate) fn run_cli<'app>( + fs: DynRef<'app, dyn FileSystem>, + console: &'app mut dyn Console, + args: bpaf::Args, +) -> Result<(), CliDiagnostic> { + use pgt_cli::SocketTransport; + use pgt_lsp::ServerFactory; + use pgt_workspace::{WorkspaceRef, workspace}; + use tokio::{ + io::{duplex, split}, + runtime::Runtime, + }; + + let factory = ServerFactory::default(); + let connection = factory.create(None); + + let runtime = Runtime::new().expect("failed to create runtime"); + + let (client, server) = duplex(4096); + let (stdin, stdout) = split(server); + runtime.spawn(connection.accept(stdin, stdout)); + + let (client_read, client_write) = split(client); + let transport = SocketTransport::open(runtime, client_read, client_write); + + let workspace = workspace::client(transport).unwrap(); + let app = App::new(fs, console, WorkspaceRef::Owned(workspace)); + + let mut session = CliSession { app }; + let command = pgt_command().run_inner(args); + match command { + Ok(command) => session.run(command), + Err(failure) => { + if let ParseFailure::Stdout(help, _) = &failure { + let console = &mut session.app.console; + console.log(markup! {{help.to_string()}}); + Ok(()) + } else { + Err(CliDiagnostic::parse_error_bpaf(failure)) + } + } + } +} diff --git a/crates/pgt_configuration/src/analyser/linter/rules.rs b/crates/pgt_configuration/src/analyser/linter/rules.rs index 6af78eeb8..14d796bf8 100644 --- a/crates/pgt_configuration/src/analyser/linter/rules.rs +++ b/crates/pgt_configuration/src/analyser/linter/rules.rs @@ -46,7 +46,7 @@ impl std::str::FromStr for RuleGroup { #[cfg_attr(feature = "schema", derive(JsonSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct Rules { - #[doc = r" It enables the lint rules recommended by PgLT. `true` by default."] + #[doc = r" It enables the lint rules recommended by Postgres Tools. `true` by default."] #[serde(skip_serializing_if = "Option::is_none")] pub recommended: Option, #[doc = r" It enables ALL rules. The rules that belong to `nursery` won't be enabled."] diff --git a/crates/pgt_flags/src/lib.rs b/crates/pgt_flags/src/lib.rs index ead9bbc05..133df7776 100644 --- a/crates/pgt_flags/src/lib.rs +++ b/crates/pgt_flags/src/lib.rs @@ -6,34 +6,34 @@ use std::env; use std::ops::Deref; use std::sync::{LazyLock, OnceLock}; -/// Returns `true` if this is an unstable build of PgLT +/// Returns `true` if this is an unstable build of Postgres Tools pub fn is_unstable() -> bool { PGT_VERSION.deref().is_none() } -/// The internal version of PgLT. This is usually supplied during the CI build +/// The internal version of Postgres Tools. This is usually supplied during the CI build pub static PGT_VERSION: LazyLock> = LazyLock::new(|| option_env!("PGT_VERSION")); -pub struct PgLTEnv { - pub pgt_log_path: PgLTEnvVariable, - pub pgt_log_prefix: PgLTEnvVariable, - pub pgt_config_path: PgLTEnvVariable, +pub struct PgTEnv { + pub pgt_log_path: PgTEnvVariable, + pub pgt_log_prefix: PgTEnvVariable, + pub pgt_config_path: PgTEnvVariable, } -pub static PGT_ENV: OnceLock = OnceLock::new(); +pub static PGT_ENV: OnceLock = OnceLock::new(); -impl PgLTEnv { +impl PgTEnv { fn new() -> Self { Self { - pgt_log_path: PgLTEnvVariable::new( + pgt_log_path: PgTEnvVariable::new( "PGT_LOG_PATH", "The directory where the Daemon logs will be saved.", ), - pgt_log_prefix: PgLTEnvVariable::new( + pgt_log_prefix: PgTEnvVariable::new( "PGT_LOG_PREFIX_NAME", "A prefix that's added to the name of the log. Default: `server.log.`", ), - pgt_config_path: PgLTEnvVariable::new( + pgt_config_path: PgTEnvVariable::new( "PGT_CONFIG_PATH", "A path to the configuration file", ), @@ -41,7 +41,7 @@ impl PgLTEnv { } } -pub struct PgLTEnvVariable { +pub struct PgTEnvVariable { /// The name of the environment variable name: &'static str, /// The description of the variable. @@ -49,7 +49,7 @@ pub struct PgLTEnvVariable { description: &'static str, } -impl PgLTEnvVariable { +impl PgTEnvVariable { fn new(name: &'static str, description: &'static str) -> Self { Self { name, description } } @@ -70,11 +70,11 @@ impl PgLTEnvVariable { } } -pub fn pgt_env() -> &'static PgLTEnv { - PGT_ENV.get_or_init(PgLTEnv::new) +pub fn pgt_env() -> &'static PgTEnv { + PGT_ENV.get_or_init(PgTEnv::new) } -impl Display for PgLTEnv { +impl Display for PgTEnv { fn fmt(&self, fmt: &mut Formatter) -> std::io::Result<()> { match self.pgt_log_path.value() { None => { diff --git a/crates/pgt_fs/src/fs.rs b/crates/pgt_fs/src/fs.rs index b652c56b2..b73aef6e4 100644 --- a/crates/pgt_fs/src/fs.rs +++ b/crates/pgt_fs/src/fs.rs @@ -1,4 +1,4 @@ -use crate::{PathInterner, PgLTPath}; +use crate::{PathInterner, PgTPath}; pub use memory::{ErrorEntry, MemoryFileSystem}; pub use os::OsFileSystem; use pgt_diagnostics::{Advices, Diagnostic, LogCategory, Visit, console}; @@ -302,18 +302,18 @@ pub trait TraversalContext: Sync { /// Checks if the traversal context can handle a particular path, used as /// an optimization to bail out of scheduling a file handler if it wouldn't /// be able to process the file anyway - fn can_handle(&self, path: &PgLTPath) -> bool; + fn can_handle(&self, path: &PgTPath) -> bool; /// This method will be called by the traversal for each file it finds /// where [TraversalContext::can_handle] returned true - fn handle_path(&self, path: PgLTPath); + fn handle_path(&self, path: PgTPath); /// This method will be called by the traversal for each file it finds /// where [TraversalContext::store_path] returned true - fn store_path(&self, path: PgLTPath); + fn store_path(&self, path: PgTPath); /// Returns the paths that should be handled - fn evaluated_paths(&self) -> BTreeSet; + fn evaluated_paths(&self) -> BTreeSet; } impl FileSystem for Arc diff --git a/crates/pgt_fs/src/fs/memory.rs b/crates/pgt_fs/src/fs/memory.rs index 55759ec8f..baffe0abf 100644 --- a/crates/pgt_fs/src/fs/memory.rs +++ b/crates/pgt_fs/src/fs/memory.rs @@ -10,7 +10,7 @@ use parking_lot::{Mutex, RawMutex, RwLock, lock_api::ArcMutexGuard}; use pgt_diagnostics::{Error, Severity}; use crate::fs::OpenOptions; -use crate::{FileSystem, PgLTPath, TraversalContext, TraversalScope}; +use crate::{FileSystem, PgTPath, TraversalContext, TraversalScope}; use super::{BoxedTraversal, ErrorKind, File, FileSystemDiagnostic}; @@ -297,7 +297,7 @@ impl<'scope> TraversalScope<'scope> for MemoryTraversalScope<'scope> { if should_process_file { let _ = ctx.interner().intern_path(path.into()); - let pgt_path = PgLTPath::new(path); + let pgt_path = PgTPath::new(path); if !ctx.can_handle(&pgt_path) { continue; } @@ -328,7 +328,7 @@ impl<'scope> TraversalScope<'scope> for MemoryTraversalScope<'scope> { } fn handle(&self, context: &'scope dyn TraversalContext, path: PathBuf) { - context.handle_path(PgLTPath::new(path)); + context.handle_path(PgTPath::new(path)); } } @@ -344,7 +344,7 @@ mod tests { use parking_lot::Mutex; use pgt_diagnostics::Error; - use crate::{FileSystem, MemoryFileSystem, PathInterner, PgLTPath, TraversalContext}; + use crate::{FileSystem, MemoryFileSystem, PathInterner, PgTPath, TraversalContext}; use crate::{OpenOptions, fs::FileSystemExt}; #[test] @@ -511,7 +511,7 @@ mod tests { struct TestContext { interner: PathInterner, - visited: Mutex>, + visited: Mutex>, } impl TraversalContext for TestContext { @@ -523,19 +523,19 @@ mod tests { panic!("unexpected error {err:?}") } - fn can_handle(&self, _: &PgLTPath) -> bool { + fn can_handle(&self, _: &PgTPath) -> bool { true } - fn handle_path(&self, path: PgLTPath) { + fn handle_path(&self, path: PgTPath) { self.visited.lock().insert(path.to_written()); } - fn store_path(&self, path: PgLTPath) { + fn store_path(&self, path: PgTPath) { self.visited.lock().insert(path); } - fn evaluated_paths(&self) -> BTreeSet { + fn evaluated_paths(&self) -> BTreeSet { let lock = self.visited.lock(); lock.clone() } @@ -556,8 +556,8 @@ mod tests { swap(&mut visited, ctx.visited.get_mut()); assert_eq!(visited.len(), 2); - assert!(visited.contains(&PgLTPath::new("dir1/file1"))); - assert!(visited.contains(&PgLTPath::new("dir1/file2"))); + assert!(visited.contains(&PgTPath::new("dir1/file1"))); + assert!(visited.contains(&PgTPath::new("dir1/file2"))); // Traverse a single file fs.traversal(Box::new(|scope| { @@ -568,6 +568,6 @@ mod tests { swap(&mut visited, ctx.visited.get_mut()); assert_eq!(visited.len(), 1); - assert!(visited.contains(&PgLTPath::new("dir2/file2"))); + assert!(visited.contains(&PgTPath::new("dir2/file2"))); } } diff --git a/crates/pgt_fs/src/fs/os.rs b/crates/pgt_fs/src/fs/os.rs index 36f3a3f7f..a2e40695d 100644 --- a/crates/pgt_fs/src/fs/os.rs +++ b/crates/pgt_fs/src/fs/os.rs @@ -2,7 +2,7 @@ use super::{BoxedTraversal, ErrorKind, File, FileSystemDiagnostic}; use crate::fs::OpenOptions; use crate::{ - FileSystem, PgLTPath, + FileSystem, PgTPath, fs::{TraversalContext, TraversalScope}, }; use pgt_diagnostics::{DiagnosticExt, Error, Severity, adapters::IoError}; @@ -190,7 +190,7 @@ impl<'scope> TraversalScope<'scope> for OsTraversalScope<'scope> { fn handle(&self, context: &'scope dyn TraversalContext, path: PathBuf) { self.scope.spawn(move |_| { - context.handle_path(PgLTPath::new(path)); + context.handle_path(PgTPath::new(path)); }); } } @@ -268,7 +268,7 @@ fn handle_any_file<'scope>( } if file_type.is_symlink() { - if !ctx.can_handle(&PgLTPath::new(path.clone())) { + if !ctx.can_handle(&PgTPath::new(path.clone())) { return; } let Ok((target_path, target_file_type)) = expand_symbolic_link(path.clone(), ctx) else { @@ -299,7 +299,7 @@ fn handle_any_file<'scope>( if let Some(file_name) = path.file_name() { let new_origin_path = old_origin_path.join(file_name); origin_path = Some(new_origin_path.clone()); - PgLTPath::new(new_origin_path) + PgTPath::new(new_origin_path) } else { ctx.push_diagnostic(Error::from(FileSystemDiagnostic { path: path.to_string_lossy().to_string(), @@ -309,7 +309,7 @@ fn handle_any_file<'scope>( return; } } else { - PgLTPath::new(&path) + PgTPath::new(&path) }; // Performing this check here let's us skip unsupported @@ -330,7 +330,7 @@ fn handle_any_file<'scope>( if file_type.is_file() { scope.spawn(move |_| { - ctx.store_path(PgLTPath::new(path)); + ctx.store_path(PgTPath::new(path)); }); return; } diff --git a/crates/pgt_fs/src/lib.rs b/crates/pgt_fs/src/lib.rs index 6c565c635..0988e7b53 100644 --- a/crates/pgt_fs/src/lib.rs +++ b/crates/pgt_fs/src/lib.rs @@ -7,7 +7,7 @@ mod path; pub use dir::ensure_cache_dir; pub use interner::PathInterner; -pub use path::PgLTPath; +pub use path::PgTPath; pub use fs::{ AutoSearchResult, ConfigName, ErrorEntry, File, FileSystem, FileSystemDiagnostic, diff --git a/crates/pgt_fs/src/path.rs b/crates/pgt_fs/src/path.rs index 9fa1b0b9b..811bebe59 100644 --- a/crates/pgt_fs/src/path.rs +++ b/crates/pgt_fs/src/path.rs @@ -85,15 +85,15 @@ impl From for FileKinds { #[derive(Debug, Clone, Eq, PartialEq, Hash, Default)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] -pub struct PgLTPath { +pub struct PgTPath { path: PathBuf, - /// 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 + /// Determines the kind of the file inside Postgres Tools. Some files are considered as configuration files, others as manifest files, and others as files to handle kind: FileKinds, /// Whether this path (usually a file) was fixed as a result of a format/lint/check command with the `--write` filag. was_written: bool, } -impl Deref for PgLTPath { +impl Deref for PgTPath { type Target = PathBuf; fn deref(&self) -> &Self::Target { @@ -101,13 +101,13 @@ impl Deref for PgLTPath { } } -impl PartialOrd for PgLTPath { +impl PartialOrd for PgTPath { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } -impl Ord for PgLTPath { +impl Ord for PgTPath { fn cmp(&self, other: &Self) -> Ordering { match self.kind.cmp(&other.kind) { Ordering::Equal => self.path.cmp(&other.path), @@ -116,7 +116,7 @@ impl Ord for PgLTPath { } } -impl PgLTPath { +impl PgTPath { pub fn new(path_to_file: impl Into) -> Self { let path = path_to_file.into(); let kind = path.file_name().map(Self::priority).unwrap_or_default(); @@ -137,7 +137,7 @@ impl PgLTPath { } } - /// Creates a new [PgLTPath], marked as fixed + /// Creates a new [PgTPath], marked as fixed pub fn to_written(&self) -> Self { Self { path: self.path.clone(), @@ -160,7 +160,7 @@ impl PgLTPath { /// Returns the contents of a file, if it exists /// /// ## Error - /// If PgLT doesn't have permissions to read the file + /// If Postgres Tools doesn't have permissions to read the file pub fn get_buffer_from_file(&mut self) -> String { // we assume we have permissions read_to_string(&self.path).expect("cannot read the file to format") diff --git a/crates/pgt_lsp/src/server.rs b/crates/pgt_lsp/src/server.rs index 544849284..17d8cf5ee 100644 --- a/crates/pgt_lsp/src/server.rs +++ b/crates/pgt_lsp/src/server.rs @@ -278,9 +278,9 @@ type Sessions = Arc>>; macro_rules! workspace_method { ( $builder:ident, $method:ident ) => { $builder = $builder.custom_method( - concat!("pglt/", stringify!($method)), + concat!("pgt/", stringify!($method)), |server: &LSPServer, params| { - let span = tracing::trace_span!(concat!("pglt/", stringify!($method)), params = ?params).or_current(); + let span = tracing::trace_span!(concat!("pgt/", stringify!($method)), params = ?params).or_current(); tracing::info!("Received request: {}", stringify!($method)); let workspace = server.session.workspace.clone(); @@ -389,12 +389,15 @@ impl ServerFactory { }); // "shutdown" is not part of the Workspace API - builder = builder.custom_method("pglt/shutdown", |server: &LSPServer, (): ()| { + builder = builder.custom_method("pgt/shutdown", |server: &LSPServer, (): ()| { info!("Sending shutdown signal"); server.session.broadcast_shutdown(); ready(Ok(Some(()))) }); + workspace_method!(builder, is_path_ignored); + workspace_method!(builder, update_settings); + workspace_method!(builder, get_file_content); workspace_method!(builder, open_file); workspace_method!(builder, change_file); workspace_method!(builder, close_file); diff --git a/crates/pgt_lsp/src/session.rs b/crates/pgt_lsp/src/session.rs index 021f0f84b..70f9ac88f 100644 --- a/crates/pgt_lsp/src/session.rs +++ b/crates/pgt_lsp/src/session.rs @@ -7,7 +7,7 @@ use futures::stream::FuturesUnordered; use pgt_analyse::RuleCategoriesBuilder; use pgt_configuration::ConfigurationPathHint; use pgt_diagnostics::{DiagnosticExt, Error}; -use pgt_fs::{FileSystem, PgLTPath}; +use pgt_fs::{FileSystem, PgTPath}; use pgt_lsp_converters::{PositionEncoding, WideEncoding, negotiated_encoding}; use pgt_workspace::Workspace; use pgt_workspace::configuration::{LoadedConfiguration, load_configuration}; @@ -342,7 +342,7 @@ impl Session { self.documents.write().unwrap().remove(url); } - pub(crate) fn file_path(&self, url: &lsp_types::Url) -> Result { + pub(crate) fn file_path(&self, url: &lsp_types::Url) -> Result { let path_to_file = match url.to_file_path() { Err(_) => { // If we can't create a path, it's probably because the file doesn't exist. @@ -352,7 +352,7 @@ impl Session { Ok(path) => path, }; - Ok(PgLTPath::new(path_to_file)) + Ok(PgTPath::new(path_to_file)) } /// True if the client supports dynamic registration of "workspace/didChangeConfiguration" requests diff --git a/crates/pgt_lsp/tests/server.rs b/crates/pgt_lsp/tests/server.rs index 4a0cd876e..b1edb4068 100644 --- a/crates/pgt_lsp/tests/server.rs +++ b/crates/pgt_lsp/tests/server.rs @@ -267,11 +267,11 @@ impl Server { .await } - /// Basic implementation of the `pglt/shutdown` request for tests + /// Basic implementation of the `pgt/shutdown` request for tests async fn pgt_shutdown(&mut self) -> Result<()> { - self.request::<_, ()>("pglt/shutdown", "_pgt_shutdown", ()) + self.request::<_, ()>("pgt/shutdown", "_pgt_shutdown", ()) .await? - .context("pglt/shutdown returned None")?; + .context("pgt/shutdown returned None")?; Ok(()) } } @@ -441,7 +441,7 @@ async fn server_shutdown() -> Result<()> { let cancellation = factory.cancellation(); let cancellation = cancellation.notified(); - // this is called when `pglt stop` is run by the user + // this is called when `postgrestools stop` is run by the user server.pgt_shutdown().await?; cancellation.await; diff --git a/crates/pgt_workspace/src/configuration.rs b/crates/pgt_workspace/src/configuration.rs index 1daa6bcec..726b23e0b 100644 --- a/crates/pgt_workspace/src/configuration.rs +++ b/crates/pgt_workspace/src/configuration.rs @@ -169,7 +169,7 @@ pub fn create_config( } })?; - // we now check if pglt is installed inside `node_modules` and if so, we use the schema from there + // we now check if postgrestools is installed inside `node_modules` and if so, we use the schema from there if VERSION == "0.0.0" { let schema_path = Path::new("./node_modules/@postgrestools/postgrestools/schema.json"); let options = OpenOptions::default().read(true); diff --git a/crates/pgt_workspace/src/dome.rs b/crates/pgt_workspace/src/dome.rs index 2ea595c09..8fa89c8b6 100644 --- a/crates/pgt_workspace/src/dome.rs +++ b/crates/pgt_workspace/src/dome.rs @@ -1,4 +1,4 @@ -use pgt_fs::PgLTPath; +use pgt_fs::PgTPath; use std::collections::BTreeSet; use std::collections::btree_set::Iter; use std::iter::{FusedIterator, Peekable}; @@ -7,16 +7,16 @@ use std::iter::{FusedIterator, Peekable}; /// specific paths like configuration files, manifests and more. #[derive(Debug, Default)] pub struct Dome { - paths: BTreeSet, + paths: BTreeSet, } impl Dome { - pub fn with_path(mut self, path: impl Into) -> Self { + pub fn with_path(mut self, path: impl Into) -> Self { self.paths.insert(path.into()); self } - pub fn new(paths: BTreeSet) -> Self { + pub fn new(paths: BTreeSet) -> Self { Self { paths } } @@ -26,17 +26,17 @@ impl Dome { } } - pub fn to_paths(self) -> BTreeSet { + pub fn to_paths(self) -> BTreeSet { self.paths } } pub struct DomeIterator<'a> { - iter: Peekable>, + iter: Peekable>, } impl<'a> DomeIterator<'a> { - pub fn next_config(&mut self) -> Option<&'a PgLTPath> { + pub fn next_config(&mut self) -> Option<&'a PgTPath> { if let Some(path) = self.iter.peek() { if path.is_config() { self.iter.next() @@ -48,7 +48,7 @@ impl<'a> DomeIterator<'a> { } } - pub fn next_ignore(&mut self) -> Option<&'a PgLTPath> { + pub fn next_ignore(&mut self) -> Option<&'a PgTPath> { if let Some(path) = self.iter.peek() { if path.is_ignore() { self.iter.next() @@ -62,7 +62,7 @@ impl<'a> DomeIterator<'a> { } impl<'a> Iterator for DomeIterator<'a> { - type Item = &'a PgLTPath; + type Item = &'a PgTPath; fn next(&mut self) -> Option { self.iter.next() diff --git a/crates/pgt_workspace/src/workspace.rs b/crates/pgt_workspace/src/workspace.rs index 20694c531..8b192bf76 100644 --- a/crates/pgt_workspace/src/workspace.rs +++ b/crates/pgt_workspace/src/workspace.rs @@ -3,7 +3,7 @@ use std::{panic::RefUnwindSafe, path::PathBuf, sync::Arc}; pub use self::client::{TransportRequest, WorkspaceClient, WorkspaceTransport}; use pgt_analyse::RuleCategories; use pgt_configuration::{PartialConfiguration, RuleSelector}; -use pgt_fs::PgLTPath; +use pgt_fs::PgTPath; use pgt_text_size::{TextRange, TextSize}; use serde::{Deserialize, Serialize}; @@ -15,7 +15,7 @@ mod server; #[derive(Debug, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct OpenFileParams { - pub path: PgLTPath, + pub path: PgTPath, pub content: String, pub version: i32, } @@ -23,13 +23,13 @@ pub struct OpenFileParams { #[derive(Debug, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct CloseFileParams { - pub path: PgLTPath, + pub path: PgTPath, } #[derive(Debug, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct ChangeFileParams { - pub path: PgLTPath, + pub path: PgTPath, pub version: i32, pub changes: Vec, } @@ -37,7 +37,7 @@ pub struct ChangeFileParams { #[derive(Debug, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct PullDiagnosticsParams { - pub path: PgLTPath, + pub path: PgTPath, pub categories: RuleCategories, pub max_diagnostics: u64, pub only: Vec, @@ -48,7 +48,7 @@ pub struct PullDiagnosticsParams { #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct GetCompletionsParams { /// The File for which a completion is requested. - pub path: PgLTPath, + pub path: PgTPath, /// The Cursor position in the file for which a completion is requested. pub position: TextSize, } @@ -78,7 +78,7 @@ impl ChangeParams { #[derive(Debug, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct IsPathIgnoredParams { - pub pgt_path: PgLTPath, + pub pgt_path: PgTPath, } #[derive(Debug, serde::Serialize, serde::Deserialize)] @@ -94,7 +94,7 @@ pub struct UpdateSettingsParams { #[derive(Debug, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct GetFileContentParams { - pub path: PgLTPath, + pub path: PgTPath, } #[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] @@ -170,7 +170,7 @@ where /// automatically on drop pub struct FileGuard<'app, W: Workspace + ?Sized> { workspace: &'app W, - path: PgLTPath, + path: PgTPath, } impl<'app, W: Workspace + ?Sized> FileGuard<'app, W> { diff --git a/crates/pgt_workspace/src/workspace/client.rs b/crates/pgt_workspace/src/workspace/client.rs index a5ae72efc..a6955c1ee 100644 --- a/crates/pgt_workspace/src/workspace/client.rs +++ b/crates/pgt_workspace/src/workspace/client.rs @@ -81,7 +81,7 @@ where } pub fn shutdown(self) -> Result<(), WorkspaceError> { - self.request("pglt/shutdown", ()) + self.request("pgt/shutdown", ()) } } @@ -90,23 +90,23 @@ where T: WorkspaceTransport + RefUnwindSafe + Send + Sync, { fn open_file(&self, params: OpenFileParams) -> Result<(), WorkspaceError> { - self.request("pglt/open_file", params) + self.request("pgt/open_file", params) } fn close_file(&self, params: CloseFileParams) -> Result<(), WorkspaceError> { - self.request("pglt/close_file", params) + self.request("pgt/close_file", params) } fn change_file(&self, params: super::ChangeFileParams) -> Result<(), WorkspaceError> { - self.request("pglt/change_file", params) + self.request("pgt/change_file", params) } fn update_settings(&self, params: super::UpdateSettingsParams) -> Result<(), WorkspaceError> { - self.request("pglt/update_settings", params) + self.request("pgt/update_settings", params) } fn is_path_ignored(&self, params: IsPathIgnoredParams) -> Result { - self.request("pglt/is_path_ignored", params) + self.request("pgt/is_path_ignored", params) } fn server_info(&self) -> Option<&ServerInfo> { @@ -114,20 +114,20 @@ where } fn get_file_content(&self, params: GetFileContentParams) -> Result { - self.request("pglt/get_file_content", params) + self.request("pgt/get_file_content", params) } fn pull_diagnostics( &self, params: super::PullDiagnosticsParams, ) -> Result { - self.request("pglt/pull_diagnostics", params) + self.request("pgt/pull_diagnostics", params) } fn get_completions( &self, params: super::GetCompletionsParams, ) -> Result { - self.request("pglt/get_completions", params) + self.request("pgt/get_completions", params) } } diff --git a/crates/pgt_workspace/src/workspace/server.rs b/crates/pgt_workspace/src/workspace/server.rs index 14e0b0df8..942ae34d6 100644 --- a/crates/pgt_workspace/src/workspace/server.rs +++ b/crates/pgt_workspace/src/workspace/server.rs @@ -11,7 +11,7 @@ use pg_query::PgQueryStore; use pgt_analyse::{AnalyserOptions, AnalysisFilter}; use pgt_analyser::{Analyser, AnalyserConfig, AnalyserContext}; use pgt_diagnostics::{Diagnostic, DiagnosticExt, Severity, serde::Diagnostic as SDiagnostic}; -use pgt_fs::{ConfigName, PgLTPath}; +use pgt_fs::{ConfigName, PgTPath}; use pgt_typecheck::TypecheckParams; use schema_cache_manager::SchemaCacheManager; use tracing::info; @@ -47,7 +47,7 @@ pub(super) struct WorkspaceServer { schema_cache: SchemaCacheManager, /// Stores the document (text content + version number) associated with a URL - documents: DashMap, + documents: DashMap, tree_sitter: TreeSitterStore, pg_query: PgQueryStore, @@ -107,7 +107,7 @@ impl WorkspaceServer { /// Check whether a file is ignored in the top-level config `files.ignore`/`files.include` fn is_ignored(&self, path: &Path) -> bool { let file_name = path.file_name().and_then(|s| s.to_str()); - // Never ignore PgLT's config file regardless `include`/`ignore` + // Never ignore Postgres Tools's config file regardless `include`/`ignore` (file_name != Some(ConfigName::pgt_jsonc())) && // Apply top-level `include`/`ignore (self.is_ignored_by_top_level_config(path) || self.is_ignored_by_migration_config(path)) @@ -126,7 +126,7 @@ impl WorkspaceServer { // `matched_path_or_any_parents` panics if `source` is not under the gitignore root. // This checks excludes absolute paths that are not a prefix of the base root. if !path.has_root() || path.starts_with(ignore.path()) { - // Because PgLT passes a list of paths, + // Because Postgres Tools passes a list of paths, // we use `matched_path_or_any_parents` instead of `matched`. ignore .matched_path_or_any_parents(path, path.is_dir()) diff --git a/crates/pgt_workspace/src/workspace/server/change.rs b/crates/pgt_workspace/src/workspace/server/change.rs index a266fc578..396cddb3f 100644 --- a/crates/pgt_workspace/src/workspace/server/change.rs +++ b/crates/pgt_workspace/src/workspace/server/change.rs @@ -420,7 +420,7 @@ mod tests { use crate::workspace::{ChangeFileParams, ChangeParams}; - use pgt_fs::PgLTPath; + use pgt_fs::PgTPath; impl Document { pub fn get_text(&self, idx: usize) -> String { @@ -451,7 +451,7 @@ mod tests { fn open_doc_with_scan_error() { let input = "select id from users;\n\n\n\nselect 1443ddwwd33djwdkjw13331333333333;"; - let d = Document::new(PgLTPath::new("test.sql"), input.to_string(), 0); + let d = Document::new(PgTPath::new("test.sql"), input.to_string(), 0); assert_eq!(d.positions.len(), 0); assert!(d.has_fatal_error()); @@ -459,10 +459,10 @@ mod tests { #[test] fn change_into_scan_error_within_statement() { - let path = PgLTPath::new("test.sql"); + let path = PgTPath::new("test.sql"); let input = "select id from users;\n\n\n\nselect 1;"; - let mut d = Document::new(PgLTPath::new("test.sql"), input.to_string(), 0); + let mut d = Document::new(PgTPath::new("test.sql"), input.to_string(), 0); assert_eq!(d.positions.len(), 2); assert!(!d.has_fatal_error()); @@ -497,10 +497,10 @@ mod tests { #[test] fn change_into_scan_error_across_statements() { - let path = PgLTPath::new("test.sql"); + let path = PgTPath::new("test.sql"); let input = "select id from users;\n\n\n\nselect 1;"; - let mut d = Document::new(PgLTPath::new("test.sql"), input.to_string(), 0); + let mut d = Document::new(PgTPath::new("test.sql"), input.to_string(), 0); assert_eq!(d.positions.len(), 2); assert!(!d.has_fatal_error()); @@ -535,10 +535,10 @@ mod tests { #[test] fn change_from_invalid_to_invalid() { - let path = PgLTPath::new("test.sql"); + let path = PgTPath::new("test.sql"); let input = "select 1d;"; - let mut d = Document::new(PgLTPath::new("test.sql"), input.to_string(), 0); + let mut d = Document::new(PgTPath::new("test.sql"), input.to_string(), 0); assert_eq!(d.positions.len(), 0); assert!(d.has_fatal_error()); @@ -569,10 +569,10 @@ mod tests { #[test] fn change_from_invalid_to_valid() { - let path = PgLTPath::new("test.sql"); + let path = PgTPath::new("test.sql"); let input = "select 1d;"; - let mut d = Document::new(PgLTPath::new("test.sql"), input.to_string(), 0); + let mut d = Document::new(PgTPath::new("test.sql"), input.to_string(), 0); assert_eq!(d.positions.len(), 0); assert!(d.has_fatal_error()); @@ -602,10 +602,10 @@ mod tests { #[test] fn within_statements() { - let path = PgLTPath::new("test.sql"); + let path = PgTPath::new("test.sql"); let input = "select id from users;\n\n\n\nselect * from contacts;"; - let mut d = Document::new(PgLTPath::new("test.sql"), input.to_string(), 0); + let mut d = Document::new(PgTPath::new("test.sql"), input.to_string(), 0); assert_eq!(d.positions.len(), 2); @@ -641,7 +641,7 @@ mod tests { #[test] fn within_statements_2() { - let path = PgLTPath::new("test.sql"); + let path = PgTPath::new("test.sql"); let input = "alter table deal alter column value drop not null;\n"; let mut d = Document::new(path.clone(), input.to_string(), 0); @@ -718,7 +718,7 @@ mod tests { #[test] fn julians_sample() { - let path = PgLTPath::new("test.sql"); + let path = PgTPath::new("test.sql"); let input = "select\n *\nfrom\n test;\n\nselect\n\nalter table test\n\ndrop column id;"; let mut d = Document::new(path.clone(), input.to_string(), 0); @@ -799,10 +799,10 @@ mod tests { #[test] fn across_statements() { - let path = PgLTPath::new("test.sql"); + let path = PgTPath::new("test.sql"); let input = "select id from users;\nselect * from contacts;"; - let mut d = Document::new(PgLTPath::new("test.sql"), input.to_string(), 0); + let mut d = Document::new(PgTPath::new("test.sql"), input.to_string(), 0); assert_eq!(d.positions.len(), 2); @@ -838,10 +838,10 @@ mod tests { #[test] fn append_whitespace_to_statement() { - let path = PgLTPath::new("test.sql"); + let path = PgTPath::new("test.sql"); let input = "select id"; - let mut d = Document::new(PgLTPath::new("test.sql"), input.to_string(), 0); + let mut d = Document::new(PgTPath::new("test.sql"), input.to_string(), 0); assert_eq!(d.positions.len(), 1); @@ -863,10 +863,10 @@ mod tests { #[test] fn apply_changes() { - let path = PgLTPath::new("test.sql"); + let path = PgTPath::new("test.sql"); let input = "select id from users;\nselect * from contacts;"; - let mut d = Document::new(PgLTPath::new("test.sql"), input.to_string(), 0); + let mut d = Document::new(PgTPath::new("test.sql"), input.to_string(), 0); assert_eq!(d.positions.len(), 2); @@ -925,7 +925,7 @@ mod tests { #[test] fn removing_newline_at_the_beginning() { - let path = PgLTPath::new("test.sql"); + let path = PgTPath::new("test.sql"); let input = "\n"; let mut d = Document::new(path.clone(), input.to_string(), 1); @@ -965,7 +965,7 @@ mod tests { #[test] fn apply_changes_at_end_of_statement() { - let path = PgLTPath::new("test.sql"); + let path = PgTPath::new("test.sql"); let input = "select id from\nselect * from contacts;"; let mut d = Document::new(path.clone(), input.to_string(), 1); @@ -997,7 +997,7 @@ mod tests { #[test] fn apply_changes_replacement() { - let path = PgLTPath::new("test.sql"); + let path = PgTPath::new("test.sql"); let mut doc = Document::new(path.clone(), "".to_string(), 0); @@ -1119,7 +1119,7 @@ mod tests { #[test] fn apply_changes_within_statement() { let input = "select id from users;\nselect * from contacts;"; - let path = PgLTPath::new("test.sql"); + let path = PgTPath::new("test.sql"); let mut doc = Document::new(path.clone(), input.to_string(), 0); @@ -1170,7 +1170,7 @@ mod tests { #[test] fn remove_outside_of_content() { - let path = PgLTPath::new("test.sql"); + let path = PgTPath::new("test.sql"); let input = "select id from contacts;\n\nselect * from contacts;"; let mut d = Document::new(path.clone(), input.to_string(), 1); diff --git a/crates/pgt_workspace/src/workspace/server/document.rs b/crates/pgt_workspace/src/workspace/server/document.rs index a95a5d56e..d77d9e979 100644 --- a/crates/pgt_workspace/src/workspace/server/document.rs +++ b/crates/pgt_workspace/src/workspace/server/document.rs @@ -1,12 +1,12 @@ use pgt_diagnostics::{Diagnostic, DiagnosticExt, Severity, serde::Diagnostic as SDiagnostic}; -use pgt_fs::PgLTPath; +use pgt_fs::PgTPath; use pgt_text_size::{TextRange, TextSize}; /// Global unique identifier for a statement #[derive(Debug, Hash, Eq, PartialEq, Clone)] pub(crate) struct Statement { /// Path of the document - pub(crate) path: PgLTPath, + pub(crate) path: PgTPath, /// Unique id within the document pub(crate) id: StatementId, } @@ -16,7 +16,7 @@ pub type StatementId = usize; type StatementPos = (StatementId, TextRange); pub(crate) struct Document { - pub(crate) path: PgLTPath, + pub(crate) path: PgTPath, pub(crate) content: String, pub(crate) version: i32, @@ -28,7 +28,7 @@ pub(crate) struct Document { } impl Document { - pub(crate) fn new(path: PgLTPath, content: String, version: i32) -> Self { + pub(crate) fn new(path: PgTPath, content: String, version: i32) -> Self { let mut id_generator = IdGenerator::new(); let (ranges, diagnostics) = split_with_diagnostics(&content, None); diff --git a/docs/checking_migrations.md b/docs/checking_migrations.md index 56596b0f1..6f552f6ed 100644 --- a/docs/checking_migrations.md +++ b/docs/checking_migrations.md @@ -5,7 +5,7 @@ Postgres Language Tools comes with a `check` command that can be integrated into To run it, simply point at your migrations directory. ```sh -pglt check supabase/migrations +postgrestools check supabase/migrations ``` When you are setting it up in an existing project, you might want to ignore all migrations that are already applied. To do so, add `migrationsDir` and `after` to your `postgrestools.jsonc` file @@ -23,7 +23,7 @@ When you are setting it up in an existing project, you might want to ignore all Alternatively, pass them directly. ``` -pglt check supabase/migrations --migrations-dir="supabase/migrations" --after=1740868021 +postgrestools check supabase/migrations --migrations-dir="supabase/migrations" --after=1740868021 ``` This will only check migrations after the specified timestamp. diff --git a/docs/cli_reference.md b/docs/cli_reference.md index 3a91f53bf..f87807898 100644 --- a/docs/cli_reference.md +++ b/docs/cli_reference.md @@ -69,7 +69,7 @@ Shows the version information and quit. - **` --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`** — - Tell PgLT to exit with an error code if some diagnostics emit warnings. + Tell Postgres Tools to exit with an error code if some diagnostics emit warnings. - **` --reporter`**=_``_ — Allows to change how diagnostics and summary are reported. - **` --log-level`**=_``_ — @@ -83,7 +83,7 @@ Shows the version information and quit. How the log should look like. [default: pretty] - **` --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. + The level of diagnostics to show. In order, from the lowest to the most important: info, warn, error. Passing `--diagnostic-level=error` will cause Postgres Tools to print only diagnostics that contain only errors. [default: info] **Available options:** @@ -152,7 +152,7 @@ Runs everything to the requested files. - **` --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`** — - Tell PgLT to exit with an error code if some diagnostics emit warnings. + Tell Postgres Tools to exit with an error code if some diagnostics emit warnings. - **` --reporter`**=_``_ — Allows to change how diagnostics and summary are reported. - **` --log-level`**=_``_ — @@ -166,7 +166,7 @@ Runs everything to the requested files. How the log should look like. [default: pretty] - **` --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. + The level of diagnostics to show. In order, from the lowest to the most important: info, warn, error. Passing `--diagnostic-level=error` will cause Postgres Tools to print only diagnostics that contain only errors. [default: info] **Available positional items:** diff --git a/docs/codegen/src/cli_doc.rs b/docs/codegen/src/cli_doc.rs index 4c178e3fb..47dd5ad7f 100644 --- a/docs/codegen/src/cli_doc.rs +++ b/docs/codegen/src/cli_doc.rs @@ -8,8 +8,11 @@ pub fn generate_cli_doc(docs_dir: &Path) -> anyhow::Result<()> { let content = fs::read_to_string(&file_path)?; - let new_content = - utils::replace_section(&content, "CLI_REF", &pgt_command().render_markdown("pglt")); + let new_content = utils::replace_section( + &content, + "CLI_REF", + &pgt_command().render_markdown("postgrestools"), + ); fs::write(file_path, &new_content)?; diff --git a/docs/index.md b/docs/index.md index 1a19bcd2c..a2868a835 100644 --- a/docs/index.md +++ b/docs/index.md @@ -32,7 +32,7 @@ Our current focus is on refining and enhancing these core features while buildin We recommend that you create a `postgrestools.jsonc` configuration file for each project. This eliminates the need to repeat the CLI options each time you run a command, and ensures that we use the same configuration in your editor. Some options are also only available from a configuration file. If you are happy with the defaults, you don’t need to create a configuration file. To create the `postgrestools.jsonc` file, run the `init` command in the root folder of your project: ```sh -pglt init +postgrestools init ``` After running the `init` command, you’ll have a `postgrestools.jsonc` file in your directory: @@ -77,7 +77,7 @@ You can use the language tools either via CLI or a Language Server. The CLI exposes a simple `check` command that will run all checks on the given files or paths. ```sh -pglt check myfile.sql +postgrestools check myfile.sql ``` Make sure to check out the other options. We will provide guides for specific use cases like linting migration files soon. diff --git a/docs/schemas/0.0.0/schema.json b/docs/schemas/0.0.0/schema.json index 85c6d0808..2f57a63d4 100644 --- a/docs/schemas/0.0.0/schema.json +++ b/docs/schemas/0.0.0/schema.json @@ -276,7 +276,7 @@ ] }, "recommended": { - "description": "It enables the lint rules recommended by PgLT. `true` by default.", + "description": "It enables the lint rules recommended by Postgres Tools. `true` by default.", "type": [ "boolean", "null" diff --git a/docs/schemas/latest/schema.json b/docs/schemas/latest/schema.json index 85c6d0808..2f57a63d4 100644 --- a/docs/schemas/latest/schema.json +++ b/docs/schemas/latest/schema.json @@ -276,7 +276,7 @@ ] }, "recommended": { - "description": "It enables the lint rules recommended by PgLT. `true` by default.", + "description": "It enables the lint rules recommended by Postgres Tools. `true` by default.", "type": [ "boolean", "null" diff --git a/mkdocs.yml b/mkdocs.yml index 0e439fcce..e744f81b2 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -1,5 +1,5 @@ site_name: Postgres Language Tools -site_url: https://pglt.github.io +site_url: https://pgtools.dev site_description: A collection of language tools and a Language Server Protocol (LSP) implementation for Postgres, focusing on developer experience and reliable SQL tooling. repo_name: supabase-community/postgres_lsp diff --git a/packages/@postgrestools/backend-jsonrpc/src/workspace.ts b/packages/@postgrestools/backend-jsonrpc/src/workspace.ts index 926477c8f..4aea83cec 100644 --- a/packages/@postgrestools/backend-jsonrpc/src/workspace.ts +++ b/packages/@postgrestools/backend-jsonrpc/src/workspace.ts @@ -1,11 +1,11 @@ // Generated file, do not edit by hand, see `xtask/codegen` import type { Transport } from "./transport"; export interface IsPathIgnoredParams { - pgt_path: PgLTPath; + pgt_path: PgTPath; } -export interface PgLTPath { +export interface PgTPath { /** - * 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 + * Determines the kind of the file inside Postgres Tools. Some files are considered as configuration files, others as manifest files, and others as files to handle */ kind: FileKind; path: string; @@ -20,13 +20,13 @@ export type FileKind = FileKind2[]; */ export type FileKind2 = "Config" | "Ignore" | "Inspectable" | "Handleable"; export interface GetFileContentParams { - path: PgLTPath; + path: PgTPath; } export interface PullDiagnosticsParams { categories: RuleCategories; max_diagnostics: number; only: RuleCode[]; - path: PgLTPath; + path: PgTPath; skip: RuleCode[]; } export type RuleCategories = RuleCategory[]; @@ -173,7 +173,7 @@ export interface GetCompletionsParams { /** * The File for which a completion is requested. */ - path: PgLTPath; + path: PgTPath; /** * The Cursor position in the file for which a completion is requested. */ @@ -337,7 +337,7 @@ export interface Rules { */ all?: boolean; /** - * It enables the lint rules recommended by PostgresTools. `true` by default. + * It enables the lint rules recommended by Postgres Tools. `true` by default. */ recommended?: boolean; safety?: Safety; @@ -388,12 +388,12 @@ export interface RuleWithOptions_for_Null { } export interface OpenFileParams { content: string; - path: PgLTPath; + path: PgTPath; version: number; } export interface ChangeFileParams { changes: ChangeParams[]; - path: PgLTPath; + path: PgTPath; version: number; } export interface ChangeParams { @@ -404,7 +404,7 @@ export interface ChangeParams { text: string; } export interface CloseFileParams { - path: PgLTPath; + path: PgTPath; } export type Configuration = PartialConfiguration; export interface Workspace { @@ -423,28 +423,28 @@ export interface Workspace { export function createWorkspace(transport: Transport): Workspace { return { isPathIgnored(params) { - return transport.request("pglt/is_path_ignored", params); + return transport.request("pgt/is_path_ignored", params); }, getFileContent(params) { - return transport.request("pglt/get_file_content", params); + return transport.request("pgt/get_file_content", params); }, pullDiagnostics(params) { - return transport.request("pglt/pull_diagnostics", params); + return transport.request("pgt/pull_diagnostics", params); }, getCompletions(params) { - return transport.request("pglt/get_completions", params); + return transport.request("pgt/get_completions", params); }, updateSettings(params) { - return transport.request("pglt/update_settings", params); + return transport.request("pgt/update_settings", params); }, openFile(params) { - return transport.request("pglt/open_file", params); + return transport.request("pgt/open_file", params); }, changeFile(params) { - return transport.request("pglt/change_file", params); + return transport.request("pgt/change_file", params); }, closeFile(params) { - return transport.request("pglt/close_file", params); + return transport.request("pgt/close_file", params); }, destroy() { transport.destroy(); diff --git a/pyproject.toml b/pyproject.toml index a45043255..73ee0fa82 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,5 +1,5 @@ [project] -name = "pglt" +name = "postgrestools" version = "0.1.0" description = "A collection of language tools and a Language Server Protocol (LSP) implementation for Postgres, focusing on developer experience and reliable SQL tooling." readme = "README.md" diff --git a/xtask/codegen/src/generate_bindings.rs b/xtask/codegen/src/generate_bindings.rs index 262242fe8..4b66fd004 100644 --- a/xtask/codegen/src/generate_bindings.rs +++ b/xtask/codegen/src/generate_bindings.rs @@ -14,7 +14,8 @@ use pgt_workspace::workspace_types::{generate_type, methods, ModuleQueue}; use xtask::{project_root, Mode, Result}; pub fn generate_bindings(mode: Mode) -> Result<()> { - let bindings_path = project_root().join("packages/@pglt/backend-jsonrpc/src/workspace.ts"); + let bindings_path = + project_root().join("packages/@postgrestools/backend-jsonrpc/src/workspace.ts"); let methods = methods(); let mut declarations = Vec::new(); @@ -125,7 +126,7 @@ pub fn generate_bindings(mode: Mode) -> Result<()> { [ AnyJsCallArgument::AnyJsExpression( AnyJsExpression::AnyJsLiteralExpression( - AnyJsLiteralExpression::JsStringLiteralExpression(make::js_string_literal_expression(make::js_string_literal(&format!("pglt/{}", method.name)))), + AnyJsLiteralExpression::JsStringLiteralExpression(make::js_string_literal_expression(make::js_string_literal(&format!("pgt/{}", method.name)))), ), ), AnyJsCallArgument::AnyJsExpression( diff --git a/xtask/codegen/src/generate_configuration.rs b/xtask/codegen/src/generate_configuration.rs index 9fd3d8c02..2c0820c46 100644 --- a/xtask/codegen/src/generate_configuration.rs +++ b/xtask/codegen/src/generate_configuration.rs @@ -299,7 +299,7 @@ fn generate_for_groups( #[cfg_attr(feature = "schema", derive(JsonSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct Rules { - /// It enables the lint rules recommended by PgLT. `true` by default. + /// It enables the lint rules recommended by Postgres Tools. `true` by default. #[serde(skip_serializing_if = "Option::is_none")] pub recommended: Option, diff --git a/xtask/codegen/src/generate_new_analyser_rule.rs b/xtask/codegen/src/generate_new_analyser_rule.rs index 37ca7dae7..6fecdff77 100644 --- a/xtask/codegen/src/generate_new_analyser_rule.rs +++ b/xtask/codegen/src/generate_new_analyser_rule.rs @@ -108,7 +108,7 @@ pub fn generate_new_analyser_rule(category: Category, rule_name: &str, group: &s // We sort rules to reduce conflicts between contributions made in parallel. let rule_line = match category { Category::Lint => format!( - r#" "lint/{group}/{rule_name_camel}": "https://pglt.dev/linter/rules/{kebab_case_rule}","# + r#" "lint/{group}/{rule_name_camel}": "https://pgtools.dev/linter/rules/{kebab_case_rule}","# ), }; let lint_start = match category {