Skip to content

Commit f5173d7

Browse files
authoredMar 30, 2025
chore: clean cargo check and cargo clippy (#277)
1 parent 68b4424 commit f5173d7

File tree

33 files changed

+138
-344
lines changed

33 files changed

+138
-344
lines changed
 

‎.github/workflows/pull_request.yml

-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ concurrency:
2020
cancel-in-progress: true
2121

2222
env:
23-
RUSTFLAGS: -A dead_code
2423
RUST_LOG: info
2524
RUST_BACKTRACE: 1
2625
RUSTUP_WINDOWS_PATH_ADD_BIN: 1

‎.github/workflows/release.yml

-3
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,6 @@ permissions:
77
contents: write
88

99
env:
10-
# Ultimately, we shouldn't ignore warnings.
11-
# We need to pass it as an ENV because inlining doesn't work on Windows.
12-
RUSTFLAGS: -A dead_code
1310
# Need these guys for cross-compilation
1411
CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER: aarch64-linux-gnu-gcc
1512
CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER: aarch64-linux-gnu-gcc

‎crates/pgt_analyse/src/rule.rs

-4
Original file line numberDiff line numberDiff line change
@@ -260,10 +260,6 @@ impl RuleDiagnostic {
260260
self.footer(LogCategory::Warn, msg)
261261
}
262262

263-
pub(crate) fn span(&self) -> Option<TextRange> {
264-
self.span
265-
}
266-
267263
pub fn advices(&self) -> &RuleAdvice {
268264
&self.rule_advice
269265
}

‎crates/pgt_cli/src/commands/check.rs

-4
Original file line numberDiff line numberDiff line change
@@ -61,10 +61,6 @@ impl CommandRunner for CheckCommandPayload {
6161
self.stdin_file_path.as_deref()
6262
}
6363

64-
fn should_write(&self) -> bool {
65-
false
66-
}
67-
6864
fn get_execution(
6965
&self,
7066
cli_options: &CliOptions,

‎crates/pgt_cli/src/commands/daemon.rs

+1-28
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use crate::{
55
use pgt_console::{ConsoleExt, markup};
66
use pgt_lsp::ServerFactory;
77
use pgt_workspace::{TransportError, WorkspaceError, workspace::WorkspaceClient};
8-
use std::{env, fs, path::PathBuf};
8+
use std::{env, path::PathBuf};
99
use tokio::io;
1010
use tokio::runtime::Runtime;
1111
use tracing::subscriber::Interest;
@@ -175,33 +175,6 @@ async fn start_lsp_proxy(
175175
}
176176
}
177177

178-
pub(crate) fn read_most_recent_log_file(
179-
log_path: Option<PathBuf>,
180-
log_file_name_prefix: String,
181-
) -> io::Result<Option<String>> {
182-
let pgt_log_path = log_path.unwrap_or(default_pgt_log_path());
183-
184-
let most_recent = fs::read_dir(pgt_log_path)?
185-
.flatten()
186-
.filter(|file| file.file_type().is_ok_and(|ty| ty.is_file()))
187-
.filter_map(|file| {
188-
match file
189-
.file_name()
190-
.to_str()?
191-
.split_once(log_file_name_prefix.as_str())
192-
{
193-
Some((_, date_part)) if date_part.split('-').count() == 4 => Some(file.path()),
194-
_ => None,
195-
}
196-
})
197-
.max();
198-
199-
match most_recent {
200-
Some(file) => Ok(Some(fs::read_to_string(file)?)),
201-
None => Ok(None),
202-
}
203-
}
204-
205178
/// Set up the [tracing]-based logging system for the server
206179
/// The events received by the subscriber are filtered at the `info` level,
207180
/// then printed using the [HierarchicalLayer] layer, and the resulting text

‎crates/pgt_cli/src/commands/mod.rs

+1-9
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ use pgt_workspace::workspace::UpdateSettingsParams;
1515
use pgt_workspace::{DynRef, Workspace, WorkspaceError};
1616
use std::ffi::OsString;
1717
use std::path::PathBuf;
18-
1918
pub(crate) mod check;
2019
pub(crate) mod clean;
2120
pub(crate) mod daemon;
@@ -24,6 +23,7 @@ pub(crate) mod version;
2423

2524
#[derive(Debug, Clone, Bpaf)]
2625
#[bpaf(options, version(VERSION))]
26+
#[allow(clippy::large_enum_variant)]
2727
/// Postgres Tools official CLI. Use it to check the health of your project or run it to check single files.
2828
pub enum PgtCommand {
2929
/// Shows the version information and quit.
@@ -338,9 +338,6 @@ pub(crate) trait CommandRunner: Sized {
338338
/// It returns the file path to use in `stdin` mode.
339339
fn get_stdin_file_path(&self) -> Option<&str>;
340340

341-
/// Whether the command should write the files.
342-
fn should_write(&self) -> bool;
343-
344341
/// Returns the [Execution] mode.
345342
fn get_execution(
346343
&self,
@@ -357,11 +354,6 @@ pub(crate) trait CommandRunner: Sized {
357354
fn check_incompatible_arguments(&self) -> Result<(), CliDiagnostic> {
358355
Ok(())
359356
}
360-
361-
/// Checks whether the configuration has errors.
362-
fn should_validate_configuration_diagnostics(&self) -> bool {
363-
true
364-
}
365357
}
366358

367359
fn get_files_to_process_with_cli_options(

‎crates/pgt_cli/src/diagnostics.rs

-20
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
use pgt_console::fmt::Display;
21
use pgt_console::markup;
32
use pgt_diagnostics::adapters::{BpafError, IoError, SerdeJsonError};
43
use pgt_diagnostics::{
@@ -231,25 +230,6 @@ pub struct IncompatibleEndConfiguration {
231230
)]
232231
pub struct NoFilesWereProcessed;
233232

234-
#[derive(Debug, Diagnostic)]
235-
#[diagnostic(
236-
category = "internalError/fs",
237-
severity = Warning,
238-
tags(DEPRECATED_CODE)
239-
)]
240-
pub struct DeprecatedArgument {
241-
#[message]
242-
pub message: MessageAndDescription,
243-
}
244-
245-
impl DeprecatedArgument {
246-
pub fn new(message: impl Display) -> Self {
247-
Self {
248-
message: MessageAndDescription::from(markup! {{message}}.to_owned()),
249-
}
250-
}
251-
}
252-
253233
#[derive(Debug, Diagnostic)]
254234
pub enum ReportDiagnostic {
255235
/// Emitted when trying to serialise the report

‎crates/pgt_cli/src/execute/diagnostics.rs

+1
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ pub(crate) trait ResultExt {
1919
code: &'static Category,
2020
) -> Result<Self::Result, Error>;
2121

22+
#[allow(unused)]
2223
fn with_file_path_and_code_and_tags(
2324
self,
2425
file_path: String,

‎crates/pgt_cli/src/execute/mod.rs

+4-23
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,10 @@ use crate::reporter::junit::{JunitReporter, JunitReporterVisitor};
1111
use crate::reporter::terminal::{ConsoleReporter, ConsoleReporterVisitor};
1212
use crate::{CliDiagnostic, CliSession, DiagnosticsPayload, Reporter};
1313
use pgt_diagnostics::{Category, category};
14-
use pgt_fs::PgTPath;
1514
use std::borrow::Borrow;
1615
use std::ffi::OsString;
1716
use std::fmt::{Display, Formatter};
18-
use std::path::{Path, PathBuf};
17+
use std::path::PathBuf;
1918
use tracing::info;
2019

2120
/// Useful information during the traversal of files and virtual content
@@ -37,25 +36,17 @@ impl Execution {
3736
}
3837
}
3938

40-
#[derive(Debug, Clone, Copy)]
41-
pub enum ExecutionEnvironment {
42-
GitHub,
43-
}
44-
4539
/// A type that holds the information to execute the CLI via `stdin
4640
#[derive(Debug, Clone)]
4741
pub struct Stdin(
42+
#[allow(unused)]
4843
/// The virtual path to the file
4944
PathBuf,
5045
/// The content of the file
5146
String,
5247
);
5348

5449
impl Stdin {
55-
fn as_path(&self) -> &Path {
56-
self.0.as_path()
57-
}
58-
5950
fn as_content(&self) -> &str {
6051
self.1.as_str()
6152
}
@@ -170,10 +161,6 @@ impl Execution {
170161
}
171162
}
172163

173-
pub(crate) const fn is_dummy(&self) -> bool {
174-
matches!(self.traversal_mode, TraversalMode::Dummy)
175-
}
176-
177164
/// Whether the traversal mode requires write access to files
178165
pub(crate) const fn requires_write_access(&self) -> bool {
179166
match self.traversal_mode {
@@ -202,6 +189,7 @@ impl Execution {
202189
false
203190
}
204191

192+
#[allow(unused)]
205193
/// Returns [true] if the user used the `--write`/`--fix` option
206194
pub(crate) fn is_write(&self) -> bool {
207195
match self.traversal_mode {
@@ -232,14 +220,7 @@ pub fn execute_mode(
232220

233221
// don't do any traversal if there's some content coming from stdin
234222
if let Some(stdin) = execution.as_stdin_file() {
235-
let pgt_path = PgTPath::new(stdin.as_path());
236-
std_in::run(
237-
session,
238-
&execution,
239-
pgt_path,
240-
stdin.as_content(),
241-
cli_options.verbose,
242-
)
223+
std_in::run(session, stdin.as_content())
243224
} else {
244225
let TraverseResult {
245226
summary,

‎crates/pgt_cli/src/execute/process_file.rs

+11-19
Original file line numberDiff line numberDiff line change
@@ -15,29 +15,34 @@ pub(crate) enum FileStatus {
1515
Changed,
1616
/// File unchanged, and it was a success
1717
Unchanged,
18+
1819
/// While handling the file, something happened
20+
#[allow(unused)]
1921
Message(Message),
22+
2023
/// A match was found while searching a file
24+
#[allow(unused)]
2125
SearchResult(usize, Message),
26+
2227
/// File ignored, it should not be count as "handled"
28+
#[allow(unused)]
2329
Ignored,
30+
2431
/// Files that belong to other tools and shouldn't be touched
32+
#[allow(unused)]
2533
Protected(String),
2634
}
2735

28-
impl FileStatus {
29-
pub const fn is_changed(&self) -> bool {
30-
matches!(self, Self::Changed)
31-
}
32-
}
33-
3436
/// Wrapper type for messages that can be printed during the traversal process
3537
#[derive(Debug)]
3638
pub(crate) enum Message {
39+
#[allow(unused)]
3740
SkippedFixes {
3841
/// Suggested fixes skipped during the lint traversal
3942
skipped_suggested_fixes: u32,
4043
},
44+
45+
#[allow(unused)]
4146
Failure,
4247
Error(Error),
4348
Diagnostics {
@@ -48,19 +53,6 @@ pub(crate) enum Message {
4853
},
4954
}
5055

51-
impl Message {
52-
pub(crate) const fn is_failure(&self) -> bool {
53-
matches!(self, Message::Failure)
54-
}
55-
}
56-
57-
#[derive(Debug)]
58-
pub(crate) enum DiffKind {
59-
Format,
60-
OrganizeImports,
61-
Assists,
62-
}
63-
6456
impl<D> From<D> for Message
6557
where
6658
Error: From<D>,

‎crates/pgt_cli/src/execute/process_file/workspace_file.rs

+1-5
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ use pgt_diagnostics::{Error, category};
44
use pgt_fs::{File, OpenOptions, PgTPath};
55
use pgt_workspace::workspace::{ChangeParams, FileGuard, OpenFileParams};
66
use pgt_workspace::{Workspace, WorkspaceError};
7-
use std::ffi::OsStr;
87
use std::path::{Path, PathBuf};
98

109
/// Small wrapper that holds information and operations around the current processed file
@@ -59,11 +58,8 @@ impl<'ctx, 'app> WorkspaceFile<'ctx, 'app> {
5958
self.guard().get_file_content()
6059
}
6160

62-
pub(crate) fn as_extension(&self) -> Option<&OsStr> {
63-
self.path.extension()
64-
}
65-
6661
/// It updates the workspace file with `new_content`
62+
#[allow(dead_code)]
6763
pub(crate) fn update_file(&mut self, new_content: impl Into<String>) -> Result<(), Error> {
6864
let new_content = new_content.into();
6965

‎crates/pgt_cli/src/execute/std_in.rs

+1-11
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,10 @@
11
//! In here, there are the operations that run via standard input
22
//!
3-
use crate::execute::Execution;
43
use crate::{CliDiagnostic, CliSession};
54
use pgt_console::{ConsoleExt, markup};
6-
use pgt_fs::PgTPath;
75

8-
pub(crate) fn run<'a>(
9-
session: CliSession,
10-
mode: &'a Execution,
11-
pgt_path: PgTPath,
12-
content: &'a str,
13-
verbose: bool,
14-
) -> Result<(), CliDiagnostic> {
15-
let workspace = &*session.app.workspace;
6+
pub(crate) fn run(session: CliSession, content: &str) -> Result<(), CliDiagnostic> {
167
let console = &mut *session.app.console;
17-
let version = 0;
188

199
console.append(markup! {{content}});
2010
Ok(())

‎crates/pgt_cli/src/execute/traverse.rs

+1-4
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,7 @@ fn traverse_inputs(
188188

189189
struct DiagnosticsPrinter<'ctx> {
190190
/// Execution of the traversal
191+
#[allow(dead_code)]
191192
execution: &'ctx Execution,
192193
/// The maximum number of diagnostics the console thread is allowed to print
193194
max_diagnostics: u32,
@@ -435,10 +436,6 @@ impl TraversalOptions<'_, '_> {
435436
pub(crate) fn push_message(&self, msg: impl Into<Message>) {
436437
self.messages.send(msg.into()).ok();
437438
}
438-
439-
pub(crate) fn protected_file(&self, pgt_path: &PgTPath) {
440-
self.push_diagnostic(WorkspaceError::protected_file(pgt_path.display().to_string()).into())
441-
}
442439
}
443440

444441
impl TraversalContext for TraversalOptions<'_, '_> {

‎crates/pgt_cli/src/reporter/terminal.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -130,13 +130,13 @@ impl fmt::Display for Files {
130130
}
131131
}
132132

133-
struct SummaryDetail<'a>(pub(crate) &'a TraversalMode, usize);
133+
struct SummaryDetail(usize);
134134

135-
impl fmt::Display for SummaryDetail<'_> {
135+
impl fmt::Display for SummaryDetail {
136136
fn fmt(&self, fmt: &mut Formatter) -> io::Result<()> {
137-
if self.1 > 0 {
137+
if self.0 > 0 {
138138
fmt.write_markup(markup! {
139-
" Fixed "{Files(self.1)}"."
139+
" Fixed "{Files(self.0)}"."
140140
})
141141
} else {
142142
fmt.write_markup(markup! {
@@ -168,7 +168,7 @@ pub(crate) struct ConsoleTraversalSummary<'a>(
168168
impl fmt::Display for ConsoleTraversalSummary<'_> {
169169
fn fmt(&self, fmt: &mut Formatter) -> io::Result<()> {
170170
let summary = SummaryTotal(self.0, self.1.changed + self.1.unchanged, &self.1.duration);
171-
let detail = SummaryDetail(self.0, self.1.changed);
171+
let detail = SummaryDetail(self.1.changed);
172172
fmt.write_markup(markup!(<Info>{summary}{detail}</Info>))?;
173173

174174
if self.1.errors > 0 {

‎crates/pgt_cli/src/service/mod.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -70,11 +70,11 @@ type JsonRpcResult = Result<Box<RawValue>, TransportError>;
7070
/// This structs holds an instance of the `tokio` runtime, as well as the
7171
/// following fields:
7272
/// - `write_send` is a sender handle to the "write channel", an MPSC channel
73-
/// that's used to queue up requests to be sent to the server (for simplicity
74-
/// the requests are pushed to the channel as serialized byte buffers)
73+
/// that's used to queue up requests to be sent to the server (for simplicity
74+
/// the requests are pushed to the channel as serialized byte buffers)
7575
/// - `pending_requests` is handle to a shared hashmap where the keys are `u64`
76-
/// corresponding to request IDs, and the values are sender handles to oneshot
77-
/// channel instances that can be consumed to fulfill the associated request
76+
/// corresponding to request IDs, and the values are sender handles to oneshot
77+
/// channel instances that can be consumed to fulfill the associated request
7878
///
7979
/// Creating a new `SocketTransport` instance requires providing a `tokio`
8080
/// runtime instance as well as the "read half" and "write half" of the socket
@@ -85,7 +85,7 @@ type JsonRpcResult = Result<Box<RawValue>, TransportError>;
8585
///
8686
/// This concurrent handling of I/O is implemented using two "background tasks":
8787
/// - the `write_task` pulls outgoing messages from the "write channel" and
88-
/// writes them to the "write half" of the socket
88+
/// writes them to the "write half" of the socket
8989
/// - the `read_task` reads incoming messages from the "read half" of the
9090
/// socket, then looks up a request with an ID corresponding to the received
9191
/// message in the "pending requests" map. If a pending request is found, it's

‎crates/pgt_cli/src/service/unix.rs

+1
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ fn get_socket_name() -> PathBuf {
2424
pgt_fs::ensure_cache_dir().join(format!("pgt-socket-{}", pgt_configuration::VERSION))
2525
}
2626

27+
#[allow(dead_code)]
2728
pub(crate) fn enumerate_pipes() -> io::Result<impl Iterator<Item = String>> {
2829
fs::read_dir(pgt_fs::ensure_cache_dir()).map(|iter| {
2930
iter.filter_map(|entry| {

‎crates/pgt_completions/src/providers/functions.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,11 @@ use crate::{
66
pub fn complete_functions(ctx: &CompletionContext, builder: &mut CompletionBuilder) {
77
let available_functions = &ctx.schema_cache.functions;
88

9-
for foo in available_functions {
9+
for func in available_functions {
1010
let item = CompletionItem {
11-
label: foo.name.clone(),
12-
score: CompletionRelevanceData::Function(foo).get_score(ctx),
13-
description: format!("Schema: {}", foo.schema),
11+
label: func.name.clone(),
12+
score: CompletionRelevanceData::Function(func).get_score(ctx),
13+
description: format!("Schema: {}", func.schema),
1414
preselected: false,
1515
kind: CompletionItemKind::Function,
1616
};

‎crates/pgt_diagnostics/src/display/diff.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -99,11 +99,11 @@ pub(super) fn print_diff(fmt: &mut fmt::Formatter<'_>, diff: &TextEdit) -> io::R
9999
/// This function scans the list of DiffOps that make up the `diff` and derives
100100
/// the following data structures:
101101
/// - `modified_lines` is the set of [LineKey] that contain at least one insert
102-
/// or delete operation
102+
/// or delete operation
103103
/// - `inserted_lines` maps a [LineKey] to the list of diff operations that
104-
/// happen on the corresponding line
104+
/// happen on the corresponding line
105105
/// - `before_line_to_after` maps line numbers in the old revision of the text
106-
/// to line numbers in the new revision
106+
/// to line numbers in the new revision
107107
/// - `after_line` counts the number of lines in the new revision of the document
108108
/// - `before_line` counts the number of lines in the old revision of the document
109109
fn process_diff_ops<'diff>(

‎crates/pgt_diagnostics_macros/src/parse.rs

+1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use syn::{
99
token::Paren,
1010
};
1111

12+
#[allow(clippy::large_enum_variant)]
1213
pub(crate) enum DeriveInput {
1314
DeriveStructInput(DeriveStructInput),
1415
DeriveEnumInput(DeriveEnumInput),

‎crates/pgt_lsp/src/adapters/line_index.rs

-10
Original file line numberDiff line numberDiff line change
@@ -67,16 +67,6 @@ impl LineIndex {
6767
}
6868
}
6969

70-
/// Return the number of lines in the index, clamped to [u32::MAX]
71-
pub fn len(&self) -> u32 {
72-
self.newlines.len().try_into().unwrap_or(u32::MAX)
73-
}
74-
75-
/// Return `true` if the index contains no lines.
76-
pub fn is_empty(&self) -> bool {
77-
self.newlines.is_empty()
78-
}
79-
8070
pub fn line_col(&self, offset: TextSize) -> Option<LineCol> {
8171
let line = self.newlines.partition_point(|&it| it <= offset) - 1;
8272
let line_start_offset = self.newlines.get(line)?;

‎crates/pgt_lsp/src/diagnostics.rs

-34
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
1-
use crate::utils::into_lsp_error;
21
use anyhow::Error;
3-
use pgt_diagnostics::print_diagnostic_to_string;
42
use pgt_workspace::WorkspaceError;
53
use std::fmt::{Display, Formatter};
6-
use tower_lsp::lsp_types::MessageType;
74

85
#[derive(Debug)]
96
pub enum LspError {
@@ -43,34 +40,3 @@ impl Display for LspError {
4340
}
4441
}
4542
}
46-
47-
/// Receives an error coming from a LSP query, and converts it into a JSON-RPC error.
48-
///
49-
/// It accepts a `Client`, so contextual messages are sent to the user.
50-
pub(crate) async fn handle_lsp_error<T>(
51-
err: LspError,
52-
client: &tower_lsp::Client,
53-
) -> Result<Option<T>, tower_lsp::jsonrpc::Error> {
54-
match err {
55-
LspError::WorkspaceError(err) => match err {
56-
// diagnostics that shouldn't raise an hard error, but send a message to the user
57-
WorkspaceError::FileIgnored(_) | WorkspaceError::FileTooLarge(_) => {
58-
let message = format!("{err}");
59-
client.log_message(MessageType::WARNING, message).await;
60-
Ok(None)
61-
}
62-
63-
_ => {
64-
let message = format!("{err}");
65-
client.log_message(MessageType::ERROR, message).await;
66-
Ok(None)
67-
}
68-
},
69-
LspError::Anyhow(err) => Err(into_lsp_error(err)),
70-
LspError::Error(err) => {
71-
let message = print_diagnostic_to_string(&err);
72-
client.log_message(MessageType::ERROR, message).await;
73-
Ok(None)
74-
}
75-
}
76-
}

‎crates/pgt_lsp/src/handlers/code_actions.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ pub fn get_actions(
6161

6262
Ok(actions
6363
.into_iter()
64-
.map(|ac| CodeActionOrCommand::CodeAction(ac))
64+
.map(CodeActionOrCommand::CodeAction)
6565
.collect())
6666
}
6767

@@ -91,7 +91,7 @@ pub async fn execute_command(
9191
path,
9292
})?;
9393

94-
/**
94+
/*
9595
* Updating all diagnostics: the changes caused by the statement execution
9696
* might affect many files.
9797
*

‎crates/pgt_lsp/src/server.rs

+3-31
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,9 @@
11
use crate::capabilities::server_capabilities;
2-
use crate::diagnostics::{LspError, handle_lsp_error};
32
use crate::handlers;
4-
use crate::session::{
5-
CapabilitySet, CapabilityStatus, ClientInformation, Session, SessionHandle, SessionKey,
6-
};
3+
use crate::session::{CapabilitySet, CapabilityStatus, Session, SessionHandle, SessionKey};
74
use crate::utils::{into_lsp_error, panic_to_lsp_error};
85
use futures::FutureExt;
96
use futures::future::ready;
10-
use pgt_diagnostics::panic::PanicError;
117
use pgt_fs::{ConfigName, FileSystem, OsFileSystem};
128
use pgt_workspace::{DynRef, Workspace, workspace};
139
use rustc_hash::FxHashMap;
@@ -88,20 +84,6 @@ impl LSPServer {
8884

8985
self.session.register_capabilities(capabilities).await;
9086
}
91-
92-
async fn map_op_error<T>(
93-
&self,
94-
result: Result<Result<Option<T>, LspError>, PanicError>,
95-
) -> LspResult<Option<T>> {
96-
match result {
97-
Ok(result) => match result {
98-
Ok(result) => Ok(result),
99-
Err(err) => handle_lsp_error(err, &self.session.client).await,
100-
},
101-
102-
Err(err) => Err(into_lsp_error(err)),
103-
}
104-
}
10587
}
10688

10789
#[tower_lsp::async_trait]
@@ -125,10 +107,6 @@ impl LanguageServer for LSPServer {
125107

126108
self.session.initialize(
127109
params.capabilities,
128-
params.client_info.map(|client_info| ClientInformation {
129-
name: client_info.name,
130-
version: client_info.version,
131-
}),
132110
params.root_uri,
133111
params.workspace_folders,
134112
);
@@ -231,13 +209,6 @@ impl LanguageServer for LSPServer {
231209
};
232210
}
233211

234-
#[tracing::instrument(level = "trace", skip(self))]
235-
async fn did_save(&self, params: DidSaveTextDocumentParams) {
236-
// handlers::text_document::did_save(&self.session, params)
237-
// .await
238-
// .ok();
239-
}
240-
241212
#[tracing::instrument(level = "trace", skip(self))]
242213
async fn did_close(&self, params: DidCloseTextDocumentParams) {
243214
handlers::text_document::did_close(&self.session, params)
@@ -270,7 +241,8 @@ impl LanguageServer for LSPServer {
270241
params: ExecuteCommandParams,
271242
) -> LspResult<Option<serde_json::Value>> {
272243
match handlers::code_actions::execute_command(&self.session, params).await {
273-
Ok(result) => LspResult::Ok(None),
244+
// we'll inform the client within `code_actions::execute_command`
245+
Ok(_) => LspResult::Ok(None),
274246
Err(err) => LspResult::Err(into_lsp_error(err)),
275247
}
276248
}

‎crates/pgt_lsp/src/session.rs

-20
Original file line numberDiff line numberDiff line change
@@ -30,14 +30,6 @@ use tower_lsp::lsp_types::{MessageType, Registration};
3030
use tower_lsp::lsp_types::{Unregistration, WorkspaceFolder};
3131
use tracing::{error, info};
3232

33-
pub(crate) struct ClientInformation {
34-
/// The name of the client
35-
pub(crate) name: String,
36-
37-
/// The version of the client
38-
pub(crate) version: Option<String>,
39-
}
40-
4133
/// Key, uniquely identifying a LSP session.
4234
#[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)]
4335
pub(crate) struct SessionKey(pub u64);
@@ -75,7 +67,6 @@ pub(crate) struct Session {
7567
struct InitializeParams {
7668
/// The capabilities provided by the client as part of [`lsp_types::InitializeParams`]
7769
client_capabilities: lsp_types::ClientCapabilities,
78-
client_information: Option<ClientInformation>,
7970
root_uri: Option<Url>,
8071
#[allow(unused)]
8172
workspace_folders: Option<Vec<WorkspaceFolder>>,
@@ -97,10 +88,6 @@ impl ConfigurationStatus {
9788
pub(crate) const fn is_error(&self) -> bool {
9889
matches!(self, ConfigurationStatus::Error)
9990
}
100-
101-
pub(crate) const fn is_loaded(&self) -> bool {
102-
matches!(self, ConfigurationStatus::Loaded)
103-
}
10491
}
10592

10693
impl TryFrom<u8> for ConfigurationStatus {
@@ -176,13 +163,11 @@ impl Session {
176163
pub(crate) fn initialize(
177164
&self,
178165
client_capabilities: lsp_types::ClientCapabilities,
179-
client_information: Option<ClientInformation>,
180166
root_uri: Option<Url>,
181167
workspace_folders: Option<Vec<WorkspaceFolder>>,
182168
) {
183169
let result = self.initialize_params.set(InitializeParams {
184170
client_capabilities,
185-
client_information,
186171
root_uri,
187172
workspace_folders,
188173
});
@@ -391,11 +376,6 @@ impl Session {
391376
}
392377
}
393378

394-
/// Returns a reference to the client information for this session
395-
pub(crate) fn client_information(&self) -> Option<&ClientInformation> {
396-
self.initialize_params.get()?.client_information.as_ref()
397-
}
398-
399379
/// Returns a reference to the client capabilities for this session
400380
pub(crate) fn client_capabilities(&self) -> Option<&ClientCapabilities> {
401381
self.initialize_params

‎crates/pgt_lsp/src/utils.rs

+75-73
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ use pgt_console::fmt::Termcolor;
66
use pgt_console::fmt::{self, Formatter};
77
use pgt_diagnostics::termcolor::NoColor;
88
use pgt_diagnostics::{Diagnostic, DiagnosticTags, Location, PrintDescription, Severity, Visit};
9-
use pgt_text_edit::{CompressedOp, DiffOp, TextEdit};
109
use pgt_text_size::{TextRange, TextSize};
1110
use std::any::Any;
1211
use std::borrow::Cow;
@@ -18,74 +17,6 @@ use tower_lsp::lsp_types;
1817
use tower_lsp::lsp_types::{self as lsp, CodeDescription, Url};
1918
use tracing::error;
2019

21-
pub(crate) fn text_edit(
22-
line_index: &LineIndex,
23-
diff: TextEdit,
24-
position_encoding: PositionEncoding,
25-
offset: Option<u32>,
26-
) -> Result<Vec<lsp::TextEdit>> {
27-
let mut result: Vec<lsp::TextEdit> = Vec::new();
28-
let mut offset = if let Some(offset) = offset {
29-
TextSize::from(offset)
30-
} else {
31-
TextSize::from(0)
32-
};
33-
34-
for op in diff.iter() {
35-
match op {
36-
CompressedOp::DiffOp(DiffOp::Equal { range }) => {
37-
offset += range.len();
38-
}
39-
CompressedOp::DiffOp(DiffOp::Insert { range }) => {
40-
let start = to_lsp::position(line_index, offset, position_encoding)?;
41-
42-
// Merge with a previous delete operation if possible
43-
let last_edit = result.last_mut().filter(|text_edit| {
44-
text_edit.range.end == start && text_edit.new_text.is_empty()
45-
});
46-
47-
if let Some(last_edit) = last_edit {
48-
last_edit.new_text = diff.get_text(*range).to_string();
49-
} else {
50-
result.push(lsp::TextEdit {
51-
range: lsp::Range::new(start, start),
52-
new_text: diff.get_text(*range).to_string(),
53-
});
54-
}
55-
}
56-
CompressedOp::DiffOp(DiffOp::Delete { range }) => {
57-
let start = to_lsp::position(line_index, offset, position_encoding)?;
58-
offset += range.len();
59-
let end = to_lsp::position(line_index, offset, position_encoding)?;
60-
61-
result.push(lsp::TextEdit {
62-
range: lsp::Range::new(start, end),
63-
new_text: String::new(),
64-
});
65-
}
66-
67-
CompressedOp::EqualLines { line_count } => {
68-
let mut line_col = line_index
69-
.line_col(offset)
70-
.expect("diff length is overflowing the line count in the original file");
71-
72-
line_col.line += line_count.get() + 1;
73-
line_col.col = 0;
74-
75-
// SAFETY: This should only happen if `line_index` wasn't built
76-
// from the same string as the old revision of `diff`
77-
let new_offset = line_index
78-
.offset(line_col)
79-
.expect("diff length is overflowing the line count in the original file");
80-
81-
offset = new_offset;
82-
}
83-
}
84-
}
85-
86-
Ok(result)
87-
}
88-
8920
/// Convert an [pgt_diagnostics::Diagnostic] to a [lsp::Diagnostic], using the span
9021
/// of the diagnostic's primary label as the diagnostic range.
9122
/// Requires a [LineIndex] to convert a byte offset range to the line/col range
@@ -209,6 +140,7 @@ impl Visit for RelatedInformationVisitor<'_> {
209140
}
210141

211142
/// Convert a piece of markup into a String
143+
#[allow(unused)]
212144
fn print_markup(markup: &MarkupBuf) -> String {
213145
let mut message = Termcolor(NoColor::new(Vec::new()));
214146
fmt::Display::fmt(markup, &mut Formatter::new(&mut message))
@@ -304,11 +236,81 @@ pub(crate) fn apply_document_changes(
304236

305237
#[cfg(test)]
306238
mod tests {
307-
use crate::adapters::PositionEncoding;
308239
use crate::adapters::line_index::LineIndex;
309-
use pgt_text_edit::TextEdit;
240+
use crate::adapters::{PositionEncoding, to_lsp};
241+
use anyhow::Result;
242+
use pgt_text_edit::{CompressedOp, DiffOp, TextEdit};
243+
use pgt_text_size::TextSize;
310244
use tower_lsp::lsp_types as lsp;
311245

246+
fn text_edit(
247+
line_index: &LineIndex,
248+
diff: TextEdit,
249+
position_encoding: PositionEncoding,
250+
offset: Option<u32>,
251+
) -> Result<Vec<lsp::TextEdit>> {
252+
let mut result: Vec<lsp::TextEdit> = Vec::new();
253+
let mut offset = if let Some(offset) = offset {
254+
TextSize::from(offset)
255+
} else {
256+
TextSize::from(0)
257+
};
258+
259+
for op in diff.iter() {
260+
match op {
261+
CompressedOp::DiffOp(DiffOp::Equal { range }) => {
262+
offset += range.len();
263+
}
264+
CompressedOp::DiffOp(DiffOp::Insert { range }) => {
265+
let start = to_lsp::position(line_index, offset, position_encoding)?;
266+
267+
// Merge with a previous delete operation if possible
268+
let last_edit = result.last_mut().filter(|text_edit| {
269+
text_edit.range.end == start && text_edit.new_text.is_empty()
270+
});
271+
272+
if let Some(last_edit) = last_edit {
273+
last_edit.new_text = diff.get_text(*range).to_string();
274+
} else {
275+
result.push(lsp::TextEdit {
276+
range: lsp::Range::new(start, start),
277+
new_text: diff.get_text(*range).to_string(),
278+
});
279+
}
280+
}
281+
CompressedOp::DiffOp(DiffOp::Delete { range }) => {
282+
let start = to_lsp::position(line_index, offset, position_encoding)?;
283+
offset += range.len();
284+
let end = to_lsp::position(line_index, offset, position_encoding)?;
285+
286+
result.push(lsp::TextEdit {
287+
range: lsp::Range::new(start, end),
288+
new_text: String::new(),
289+
});
290+
}
291+
292+
CompressedOp::EqualLines { line_count } => {
293+
let mut line_col = line_index
294+
.line_col(offset)
295+
.expect("diff length is overflowing the line count in the original file");
296+
297+
line_col.line += line_count.get() + 1;
298+
line_col.col = 0;
299+
300+
// SAFETY: This should only happen if `line_index` wasn't built
301+
// from the same string as the old revision of `diff`
302+
let new_offset = line_index
303+
.offset(line_col)
304+
.expect("diff length is overflowing the line count in the original file");
305+
306+
offset = new_offset;
307+
}
308+
}
309+
}
310+
311+
Ok(result)
312+
}
313+
312314
#[test]
313315
fn test_diff_1() {
314316
const OLD: &str = "line 1 old
@@ -330,7 +332,7 @@ line 7 new";
330332
let line_index = LineIndex::new(OLD);
331333
let diff = TextEdit::from_unicode_words(OLD, NEW);
332334

333-
let text_edit = super::text_edit(&line_index, diff, PositionEncoding::Utf8, None).unwrap();
335+
let text_edit = text_edit(&line_index, diff, PositionEncoding::Utf8, None).unwrap();
334336

335337
assert_eq!(
336338
text_edit.as_slice(),
@@ -373,7 +375,7 @@ line 7 new";
373375
let line_index = LineIndex::new(OLD);
374376
let diff = TextEdit::from_unicode_words(OLD, NEW);
375377

376-
let text_edit = super::text_edit(&line_index, diff, PositionEncoding::Utf8, None).unwrap();
378+
let text_edit = text_edit(&line_index, diff, PositionEncoding::Utf8, None).unwrap();
377379

378380
assert_eq!(
379381
text_edit.as_slice(),

‎crates/pgt_test_macros/src/lib.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@ impl Arguments {
164164

165165
let span = self.pattern.lit.span();
166166
let test_name = syn::Ident::new(&test_name, span);
167-
let foo = &self.test_function;
167+
let func = &self.test_function;
168168

169169
modules.insert(
170170
path,
@@ -174,7 +174,7 @@ impl Arguments {
174174
let test_fullpath = #test_fullpath;
175175
let test_expected_fullpath = #test_expected_fullpath;
176176
let test_dir = #test_dir;
177-
#foo(test_fullpath, test_expected_fullpath, test_dir);
177+
#func(test_fullpath, test_expected_fullpath, test_dir);
178178
}
179179
},
180180
)

‎crates/pgt_text_size/src/size.rs

-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ use {
55
fmt, iter,
66
num::TryFromIntError,
77
ops::{Add, AddAssign, Sub, SubAssign},
8-
u32,
98
},
109
};
1110

‎crates/pgt_typecheck/src/diagnostics.rs

+7-3
Original file line numberDiff line numberDiff line change
@@ -30,12 +30,16 @@ struct TypecheckAdvices {
3030
column: Option<String>,
3131
data_type: Option<String>,
3232
constraint: Option<String>,
33-
line: Option<usize>,
34-
file: Option<String>,
3533
detail: Option<String>,
36-
routine: Option<String>,
3734
where_: Option<String>,
3835
hint: Option<String>,
36+
37+
#[allow(unused)]
38+
line: Option<usize>,
39+
#[allow(unused)]
40+
file: Option<String>,
41+
#[allow(unused)]
42+
routine: Option<String>,
3943
}
4044

4145
impl Advices for TypecheckAdvices {

‎crates/pgt_workspace/src/configuration.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,7 @@ pub fn strip_jsonc_comments(jsonc_input: &str) -> String {
239239
json_output.push(last_char);
240240
}
241241
} else {
242-
json_output.push_str(" ");
242+
json_output.push(' ');
243243
}
244244
last_char = Some(cur_char);
245245
}

‎crates/pgt_workspace/src/settings.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -303,7 +303,7 @@ impl From<PartialDatabaseConfiguration> for DatabaseSettings {
303303
.map(|stringset| {
304304
stringset.iter().any(|pattern| {
305305
let glob = Glob::new(pattern)
306-
.expect(format!("Invalid pattern: {}", pattern).as_str())
306+
.unwrap_or_else(|_| panic!("Invalid pattern: {}", pattern))
307307
.compile_matcher();
308308

309309
glob.is_match(format!("{}/{}", host, database))

‎crates/pgt_workspace/src/workspace/server.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -288,7 +288,7 @@ impl Workspace for WorkspaceServer {
288288
Some("Statement execution not allowed against database.".into())
289289
};
290290

291-
for (stmt, range, txt) in eligible_statements {
291+
for (stmt, _, txt) in eligible_statements {
292292
let title = format!(
293293
"Execute Statement: {}...",
294294
txt.chars().take(50).collect::<String>()
@@ -337,7 +337,7 @@ impl Workspace for WorkspaceServer {
337337
}
338338
};
339339

340-
let conn = self.connection.write().unwrap();
340+
let conn = self.connection.read().unwrap();
341341
let pool = match conn.get_pool() {
342342
Some(p) => p,
343343
None => {

‎crates/pgt_workspace/src/workspace/server/migration.rs

+1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use std::path::Path;
33
#[derive(Debug)]
44
pub(crate) struct Migration {
55
pub(crate) timestamp: u64,
6+
#[allow(unused)]
67
pub(crate) name: String,
78
}
89

‎xtask/codegen/src/generate_configuration.rs

+4-16
Original file line numberDiff line numberDiff line change
@@ -536,13 +536,7 @@ fn generate_group_struct(
536536
let rule_option_type = quote! {
537537
pgt_analyser::options::#rule_name
538538
};
539-
let rule_option = if kind == RuleCategory::Action {
540-
quote! { Option<#rule_config_type<#rule_option_type>> }
541-
} else {
542-
quote! {
543-
Option<#rule_config_type<#rule_option_type>>
544-
}
545-
};
539+
let rule_option = quote! { Option<#rule_config_type<#rule_option_type>> };
546540
schema_lines_rules.push(quote! {
547541
#[doc = #summary]
548542
#[serde(skip_serializing_if = "Option::is_none")]
@@ -570,15 +564,9 @@ fn generate_group_struct(
570564
}
571565
});
572566

573-
if kind == RuleCategory::Action {
574-
get_rule_configuration_line.push(quote! {
575-
#rule => self.#rule_identifier.as_ref().map(|conf| (conf.level(), conf.get_options()))
576-
});
577-
} else {
578-
get_rule_configuration_line.push(quote! {
579-
#rule => self.#rule_identifier.as_ref().map(|conf| (conf.level(), conf.get_options()))
580-
});
581-
}
567+
get_rule_configuration_line.push(quote! {
568+
#rule => self.#rule_identifier.as_ref().map(|conf| (conf.level(), conf.get_options()))
569+
});
582570
}
583571

584572
let group_pascal_ident = Ident::new(&to_capitalized(group), Span::call_site());

0 commit comments

Comments
 (0)
Please sign in to comment.