Skip to content

Commit

Permalink
Use anyhow.
Browse files Browse the repository at this point in the history
  • Loading branch information
rcorre committed Dec 3, 2024
1 parent 7080688 commit 7d1d88f
Show file tree
Hide file tree
Showing 8 changed files with 49 additions and 40 deletions.
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ log = "0.4.20"
env_logger = { version = "0.10.1", default-features = false }
walkdir = "2.4.0"
regex = "1"
anyhow = "1.0.93"

[dev-dependencies]
pretty_assertions = "1.4.0"
Expand Down
13 changes: 6 additions & 7 deletions src/file.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use anyhow::{Context, Result};
use std::sync::OnceLock;

type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;

fn language() -> tree_sitter::Language {
static LANGUAGE: OnceLock<tree_sitter::Language> = OnceLock::new();
*LANGUAGE.get_or_init(|| tree_sitter_protobuf::language())
Expand Down Expand Up @@ -54,7 +53,7 @@ impl File {
.set_language(language())
.expect("Error loading proto language");

let tree = parser.parse(&text, None).ok_or("Parse failed")?;
let tree = parser.parse(&text, None).context("Parse failed")?;
log::trace!("Parsed: {}", tree.root_node().to_sexp());
Ok(File { tree, text })
}
Expand All @@ -63,7 +62,7 @@ impl File {
for change in changes {
let range = change
.range
.ok_or("No range in change notification {change:?}")?;
.with_context(|| format!("No range in change notification {change:?}"))?;
let mut lines = self.text.split_inclusive("\n").peekable();
// First count bytes in all lines preceding the edit.
let start_byte = lines
Expand Down Expand Up @@ -104,7 +103,7 @@ impl File {
parser
.set_language(language())
.expect("Error loading proto language");
self.tree = parser.parse(&self.text, None).ok_or("Parse failed")?;
self.tree = parser.parse(&self.text, None).context("Parse failed")?;
log::trace!("Edited tree to: {}", self.tree.root_node().to_sexp());

Ok(())
Expand Down Expand Up @@ -251,7 +250,7 @@ impl File {
.tree
.root_node()
.named_descendant_for_point_range(pos, pos)
.ok_or(format!("No descendant for range {pos:?}"))?;
.with_context(|| format!("No descendant for range {pos:?}"))?;

log::debug!(
"Getting completion context for node={node:?} parent={:?}",
Expand Down Expand Up @@ -301,7 +300,7 @@ impl File {
.lines()
.skip(row)
.next()
.ok_or(format!("Line {row} out of range"))?
.with_context(|| format!("Line {row} out of range"))?
.chars()
.take(col)
.collect();
Expand Down
3 changes: 1 addition & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,9 @@ use lsp_types::{
DocumentSymbolResponse, GotoDefinitionParams, GotoDefinitionResponse, OneOf,
WorkspaceSymbolParams,
};
use std::error::Error;
use std::fs;

pub type Result<T> = std::result::Result<T, Box<dyn Error>>;
pub use anyhow::Result;

#[derive(Debug, serde::Deserialize)]
struct Config {
Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
fn main() -> pbls::Result<()> {
fn main() -> anyhow::Result<()> {
env_logger::init();
let (connection, io_threads) = lsp_server::Connection::stdio();
pbls::run(connection)?;
Expand Down
16 changes: 9 additions & 7 deletions src/protoc.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
use anyhow::{bail, Context, Result};
use lsp_types::{Diagnostic, DiagnosticSeverity, Range, Url};

pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;

pub fn diags(
uri: &Url,
text: &str,
proto_paths: &Vec<std::path::PathBuf>,
) -> Result<Vec<Diagnostic>> {
if uri.scheme() != "file" {
Err(format!("Unsupported URI scheme {uri}"))?;
bail!("Unsupported URI scheme {uri}");
}

let path = uri
.to_file_path()
.or(Err(format!("Failed to normalize URI path: {uri}")))?;
let Ok(path) = uri.to_file_path() else {
bail!("Failed to normalize URI path: {uri}");
};

let mut cmd = std::process::Command::new("protoc");
cmd
Expand All @@ -33,7 +32,10 @@ pub fn diags(
.map(|p| "-I".to_string() + p),
)
// Add the file we're compiling
.arg(path.to_str().ok_or(format!("Non-unicode path: {path:?}"))?);
.arg(
path.to_str()
.with_context(|| format!("Non-unicode path: {path:?}"))?,
);

log::debug!("Running protoc: {cmd:?}");
let output = cmd.output()?;
Expand Down
24 changes: 13 additions & 11 deletions src/workspace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,11 @@ use std::collections::hash_map;
use crate::file::{self};

use super::protoc;
use anyhow::{anyhow, Context, Result};
use lsp_types::{SymbolInformation, Url};
use regex::RegexBuilder;
use tree_sitter::QueryCursor;

pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;

const OPTIONS: &[&str] = &[
"cc_enable_arenas",
"cc_generic_services",
Expand Down Expand Up @@ -97,7 +96,7 @@ impl Workspace {
Ok(self
.files
.get(uri)
.ok_or(format!("File not loaded: {uri}"))?)
.with_context(|| format!("File not loaded: {uri}"))?)
}

fn find_import(&self, name: &str) -> Option<std::path::PathBuf> {
Expand All @@ -114,7 +113,7 @@ impl Workspace {
return Ok(());
};

let uri = Url::from_file_path(path.clone()).or(Err(format!("Invalid path {path:?}")))?;
let uri = Url::from_file_path(path.clone()).or(Err(anyhow!("Invalid path {path:?}")))?;
if self.files.contains_key(&uri) {
return Ok(()); // already parsed
};
Expand Down Expand Up @@ -160,7 +159,7 @@ impl Workspace {
let file = self
.files
.get_mut(uri)
.ok_or(format!("File not loaded: {uri}"))?;
.with_context(|| format!("File not loaded: {uri}"))?;
file.edit(changes)?;

let mut qc = tree_sitter::QueryCursor::new();
Expand Down Expand Up @@ -203,7 +202,7 @@ impl Workspace {

for path in paths {
log::debug!("Loading {path:?}");
let uri = Url::from_file_path(&path).or(Err(format!("Invalid path: {path:?}")))?;
let uri = Url::from_file_path(&path).or(Err(anyhow!("Invalid path: {path:?}")))?;
if let Some(file) = self.files.get(&uri) {
file
} else {
Expand Down Expand Up @@ -257,7 +256,7 @@ impl Workspace {
let file = self
.files
.get(uri)
.ok_or("Completion requested on file with no tree for {uri}")?;
.with_context(|| format!("Completion requested on file with no tree for {uri}"))?;
match file.completion_context(line, character)? {
Some(file::CompletionContext::Message(msg)) => self.complete_types(&msg, file),
Some(file::CompletionContext::Enum(_)) => Ok(None), // TODO
Expand Down Expand Up @@ -331,7 +330,7 @@ impl Workspace {
file::GotoContext::Type(t) => {
let src = self
.find_symbol(uri.clone(), file, &t)?
.ok_or("Symbol not found: {t:?}")?;
.with_context(|| format!("Symbol not found: {t:?}"))?;
let src = self.get(&src.uri)?;
let pkg = src.package();
for (uri, file) in self.files.iter() {
Expand Down Expand Up @@ -512,11 +511,14 @@ impl Workspace {

let current = std::path::Path::new(url.path())
.file_name()
.ok_or("Invalid path: {uri}")?
.with_context(|| format!("Invalid path: {url}"))?
.to_str()
.ok_or("Invalid path: {uri}")?;
.with_context(|| format!("Invalid path: {url}"))?;

let file = self.files.get(url).ok_or("File not loaded: {uri}")?;
let file = self
.files
.get(url)
.with_context(|| format!("File not loaded: {url}"))?;
let mut qc = tree_sitter::QueryCursor::new();
let existing = file
.imports(&mut qc)
Expand Down
23 changes: 11 additions & 12 deletions tests/integration_test.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use anyhow::{anyhow, bail, Context, Result};
use core::panic;
use lsp_server::{Connection, Message};
use lsp_types::notification::{
Expand All @@ -16,9 +17,7 @@ use lsp_types::{
TextDocumentItem, TextDocumentPositionParams, Url, WorkDoneProgressParams,
WorkspaceSymbolParams, WorkspaceSymbolResponse,
};
use pbls::Result;
use pretty_assertions::assert_eq;
use std::error::Error;

fn base_uri() -> Url {
Url::from_file_path(std::fs::canonicalize("./testdata/simple.proto").unwrap()).unwrap()
Expand Down Expand Up @@ -242,7 +241,7 @@ impl TestClient {
Ok(client)
}

fn recv<T>(&self) -> std::result::Result<T::Params, Box<dyn Error>>
fn recv<T>(&self) -> Result<T::Params>
where
T: lsp_types::notification::Notification,
{
Expand All @@ -251,16 +250,16 @@ impl TestClient {
.receiver
.recv_timeout(std::time::Duration::from_secs(5))?
{
Message::Request(r) => Err(format!("Expected notification, got: {r:?}"))?,
Message::Response(r) => Err(format!("Expected notification, got: {r:?}"))?,
Message::Request(r) => bail!("Expected notification, got: {r:?}"),
Message::Response(r) => bail!("Expected notification, got: {r:?}"),
Message::Notification(resp) => {
assert_eq!(resp.method, T::METHOD, "Unexpected response {resp:?}");
Ok(serde_json::from_value(resp.params)?)
}
}
}

fn request<T>(&mut self, params: T::Params) -> pbls::Result<T::Result>
fn request<T>(&mut self, params: T::Params) -> anyhow::Result<T::Result>
where
T: lsp_types::request::Request,
T::Params: serde::de::DeserializeOwned,
Expand All @@ -279,18 +278,18 @@ impl TestClient {
.receiver
.recv_timeout(std::time::Duration::from_secs(5))?
{
Message::Request(r) => Err(format!("Expected response, got: {r:?}"))?,
Message::Notification(r) => Err(format!("Expected response, got: {r:?}"))?,
Message::Request(r) => Err(anyhow!("Expected response, got: {r:?}"))?,
Message::Notification(r) => Err(anyhow!("Expected response, got: {r:?}"))?,
Message::Response(resp) if resp.error.is_some() => {
Err(format!("Got error response {:?}", resp))?
Err(anyhow!("Got error response {:?}", resp))?
}
Message::Response(resp) => Ok(serde_json::from_value(
resp.result.ok_or("Missing result from response")?,
resp.result.context("Missing result from response")?,
)?),
}
}

fn notify<T>(&self, params: T::Params) -> pbls::Result<()>
fn notify<T>(&self, params: T::Params) -> Result<()>
where
T: lsp_types::notification::Notification,
T::Params: serde::de::DeserializeOwned,
Expand All @@ -304,7 +303,7 @@ impl TestClient {
Ok(())
}

fn open(&self, uri: Url) -> pbls::Result<PublishDiagnosticsParams> {
fn open(&self, uri: Url) -> Result<PublishDiagnosticsParams> {
let text = std::fs::read_to_string(uri.path())?;
self.notify::<DidOpenTextDocument>(DidOpenTextDocumentParams {
text_document: TextDocumentItem {
Expand Down

0 comments on commit 7d1d88f

Please sign in to comment.