Skip to content

Commit

Permalink
remove anyhow
Browse files Browse the repository at this point in the history
  • Loading branch information
erasin committed Jul 7, 2024
1 parent 63a2824 commit 509c89f
Show file tree
Hide file tree
Showing 10 changed files with 49 additions and 83 deletions.
7 changes: 0 additions & 7 deletions Cargo.lock

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

1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ exclude = [".helix"]

[dependencies]
aho-corasick = "1.1.3"
anyhow = "1.0"
crossbeam-channel = "0.5"
etcetera = "0.8.0"
flexi_logger = "0.28.0"
Expand Down
4 changes: 2 additions & 2 deletions src/action.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ use ropey::Rope;
use serde::{Deserialize, Serialize};

use crate::{
errors::Error,
loader::{config_dir, Dirs},
parser::{parse, Parser, StrOrSeq},
variables::{VariableInit, Variables},
Result,
};

#[derive(Deserialize, Serialize, Clone, Debug)]
Expand Down Expand Up @@ -192,7 +192,7 @@ fn from_files(name: String, files: Vec<PathBuf>) -> Actions {
}

/// 执行
pub fn shell_exec(cmd: &str) -> Result<(), Error> {
pub fn shell_exec(cmd: &str) -> Result<()> {
let shell = if cfg!(windows) {
vec!["cmd".to_owned(), "/C".to_owned()]
} else {
Expand Down
21 changes: 10 additions & 11 deletions src/clipboard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

// Implementation reference: https://github.com/neovim/neovim/blob/f2906a4669a2eef6d7bf86a29648793d63c98949/runtime/autoload/provider/clipboard.vim#L68-L152

use anyhow::Result;
use crate::Result;
use std::borrow::Cow;

pub trait ClipboardProvider: std::fmt::Debug {
Expand Down Expand Up @@ -147,7 +147,7 @@ pub fn get_clipboard_provider() -> Box<dyn ClipboardProvider> {
#[cfg(not(target_os = "windows"))]
pub mod provider {
use super::ClipboardProvider;
use anyhow::Result;
use crate::Result;
use std::borrow::Cow;

#[cfg(feature = "term")]
Expand Down Expand Up @@ -234,7 +234,9 @@ pub mod provider {
#[cfg(not(target_arch = "wasm32"))]
pub mod command {
use super::*;
use anyhow::{bail, Context as _};

use crate::errors::Error;
use crate::Result;

#[cfg(not(any(windows, target_os = "macos")))]
pub fn is_exit_success(program: &str, args: &[&str]) -> bool {
Expand Down Expand Up @@ -283,17 +285,14 @@ pub mod provider {
let mut child = command_mut.spawn()?;

if let Some(input) = input {
let mut stdin = child.stdin.take().context("stdin is missing")?;
stdin
.write_all(input.as_bytes())
.context("couldn't write in stdin")?;
let mut stdin = child.stdin.take().ok_or(Error::ClipboardMissStdin)?;
stdin.write_all(input.as_bytes())?;
}

// TODO: add timer?
let output = child.wait_with_output()?;

if !output.status.success() {
bail!("clipboard provider {} failed", self.prg);
return Error::ClipboardFail(self.prg).into();
}

if pipe_output {
Expand Down Expand Up @@ -324,7 +323,7 @@ pub mod provider {
fn get_contents(&self) -> Result<String> {
self.get_cmd
.execute(None, true)?
.context("output is missing")
.ok_or(Error::ClipboardMissStdout.into())
}

fn set_contents(&mut self, value: String) -> Result<()> {
Expand All @@ -337,7 +336,7 @@ pub mod provider {
#[cfg(target_os = "windows")]
mod provider {
use super::ClipboardProvider;
use anyhow::Result;
use crate::Result;
use std::borrow::Cow;

#[derive(Default, Debug)]
Expand Down
54 changes: 14 additions & 40 deletions src/errors.rs
Original file line number Diff line number Diff line change
@@ -1,56 +1,30 @@
use std::io;

use crossbeam_channel::SendError;
use lsp_server::{ExtractError, Message};
use thiserror::Error;

/// 自定义错误,兼容项目错误内容
#[derive(Debug, Error, miette::Diagnostic)]
pub enum Error {
#[error(transparent)]
#[diagnostic(code(lsp::server_capabilities))]
ServerCapabilities(#[from] serde_json::Error),

#[error(transparent)]
#[diagnostic(code(lsp::server_init))]
ServerInit(#[from] lsp_server::ProtocolError),

#[error(transparent)]
#[diagnostic(code(lsp::io))]
Io(#[from] io::Error),

#[error("Unsupported LSP request: {request}")]
#[diagnostic(code(lsp::unsupported_lsp_request))]
UnsupportedLspRequest { request: String },

#[error(transparent)]
#[diagnostic(code(lsp::cast_request))]
CastRequest(#[from] ExtractError<lsp_server::Request>),

#[error(transparent)]
#[diagnostic(code(lsp::cast_notification))]
CastNotification(#[from] ExtractError<lsp_server::Notification>),

#[error(transparent)]
#[diagnostic(code(lsp::send))]
Send(#[from] SendError<Message>),

#[error(transparent)]
#[diagnostic(code(lsp::send))]
PathToUri(#[from] url::ParseError),
#[error("position {0}:{1} is out of bounds")]
PositionOutOfBounds(u32, u32),

#[error(transparent)]
Aho(#[from] aho_corasick::BuildError),
#[error("clipboard provider: stdin is missing")]
ClipboardMissStdin,

#[error(transparent)]
#[diagnostic(code(lsp::log))]
Logger(#[from] flexi_logger::FlexiLoggerError),
#[error("clipboard provider: stdout is missing")]
ClipboardMissStdout,

#[error("position {0}:{1} is out of bounds")]
PositionOutOfBounds(u32, u32),
#[error("clipboard provider {0} failed")]
ClipboardFail(&'static str),

#[error("Not Found: {0}")]
NotFound(String),
// #[error("unknown data store error")]
// Unknown,
}

impl<T> From<Error> for crate::Result<T> {
fn from(val: Error) -> Self {
Err(Box::new(val))
}
}
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
// #![allow(dead_code, unused_imports)]

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

pub mod action;
pub mod clipboard;
pub mod encoding;
Expand Down
28 changes: 14 additions & 14 deletions src/lsp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use ropey::Rope;
use crate::{
action::{shell_exec, Actions},
encoding::{get_current_word, is_field},
Result,
};
use crate::{clipboard::get_clipboard_provider, snippet::Snippets};
use crate::{encoding::get_range_content, errors::Error};
Expand Down Expand Up @@ -78,7 +79,7 @@ impl Server {
}
}

pub fn listen(&mut self, connection: &Connection) -> Result<(), Error> {
pub fn listen(&mut self, connection: &Connection) -> Result<()> {
log::info!("starting example main loop");

while let Ok(msg) = connection.receiver.recv() {
Expand Down Expand Up @@ -107,10 +108,7 @@ impl Server {
}

/// lsp 请求处理
fn handle_request(
&mut self,
request: lsp_server::Request,
) -> Result<lsp_server::Response, Error> {
fn handle_request(&mut self, request: lsp_server::Request) -> Result<lsp_server::Response> {
let id = request.id.clone();

match request.method.as_str() {
Expand Down Expand Up @@ -153,9 +151,10 @@ impl Server {

// DocumentDiagnosticRequest::METHOD
// WorkspaceDiagnosticRequest::METHOD
unsupported => Err(Error::UnsupportedLspRequest {
unsupported => Error::UnsupportedLspRequest {
request: unsupported.to_string(),
}),
}
.into(),
}

// match cast_request::<Completion>(request) {
Expand All @@ -167,7 +166,7 @@ impl Server {
}

/// lsp 提示处理
fn handle_notification(&mut self, notification: lsp_server::Notification) -> Result<(), Error> {
fn handle_notification(&mut self, notification: lsp_server::Notification) -> Result<()> {
match notification.method.as_str() {
Exit::METHOD => {
// exit
Expand All @@ -188,7 +187,7 @@ impl Server {
.insert(uri.to_string(), params.text_document.language_id);
self.lang_doc.lock().insert(uri.to_string(), doc);

Ok::<(), Error>(())
Ok(())
}

// 文件关闭
Expand Down Expand Up @@ -239,9 +238,10 @@ impl Server {
Ok(())
}

unsupported => Err(Error::UnsupportedLspRequest {
unsupported => Error::UnsupportedLspRequest {
request: unsupported.to_string(),
}),
}
.into(),
}
}

Expand Down Expand Up @@ -330,7 +330,7 @@ impl Server {
Some(actions.to_code_action_items(&variable_init))
}

fn action_resolve(&self, action: &CodeAction) -> Result<CodeAction, Error> {
fn action_resolve(&self, action: &CodeAction) -> Result<CodeAction> {
let cmd = action.clone().command.expect("unknow cmd");

shell_exec(cmd.command.as_str())?;
Expand All @@ -345,7 +345,7 @@ impl Server {
}

/// 获取 request 参数
fn cast_request<R>(request: lsp_server::Request) -> Result<R::Params, Error>
fn cast_request<R>(request: lsp_server::Request) -> Result<R::Params>
where
R: lsp_types::request::Request,
R::Params: serde::de::DeserializeOwned,
Expand All @@ -355,7 +355,7 @@ where
}

/// 获取 notification 参数
fn cast_notification<N>(notification: lsp_server::Notification) -> Result<N::Params, Error>
fn cast_notification<N>(notification: lsp_server::Notification) -> Result<N::Params>
where
N: lsp_types::notification::Notification,
N::Params: serde::de::DeserializeOwned,
Expand Down
6 changes: 3 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ use flexi_logger::{FileSpec, Logger, WriteMode};
use lsp_server::Connection;

use hx_lsp::{
errors::Error,
lsp::{server_capabilities, Server},
variables::get_time_offset,
Result,
};
use lsp_types::InitializeParams;

fn main() -> Result<(), Error> {
fn main() -> Result<()> {
if let Some(arg) = std::env::args().nth(1) {
if arg.eq("--version") {
let version = env!("CARGO_PKG_VERSION");
Expand All @@ -27,7 +27,7 @@ fn main() -> Result<(), Error> {
run_lsp_server()
}

fn run_lsp_server() -> Result<(), Error> {
fn run_lsp_server() -> Result<()> {
log::info!("hx-lsp: server up");

let (connection, io_threads) = Connection::stdio();
Expand Down
4 changes: 2 additions & 2 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::{collections::HashMap, fs::File, io::BufReader, path::PathBuf};
use json_comments::StripComments;
use serde::{de::DeserializeOwned, Deserialize, Serialize};

use crate::errors::Error;
use crate::Result;

pub trait Parser {
type Item: DeserializeOwned + Clone;
Expand All @@ -12,7 +12,7 @@ pub trait Parser {
}

/// 解析 `code-snippets json` 文件
pub fn parse<T>(lang_file_path: &PathBuf, name: String) -> Result<T, Error>
pub fn parse<T>(lang_file_path: &PathBuf, name: String) -> Result<T>
where
T: Parser + DeserializeOwned + Serialize + Clone + Default,
{
Expand Down
5 changes: 2 additions & 3 deletions src/snippet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,17 @@ use std::{
path::{Path, PathBuf},
};

use anyhow::Result;
use lsp_types::{CompletionItem, CompletionItemKind};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use std::sync::OnceLock;

use crate::{
errors::Error,
fuzzy::fuzzy_match,
loader::{config_dir, Dirs},
parser::{parse, Parser, StrOrSeq},
variables::{VariableInit, Variables},
Result,
};

/// 代码片段
Expand Down Expand Up @@ -182,7 +181,7 @@ impl Snippets {
})
}

pub fn filter(&self, word: &str) -> Result<Snippets, Error> {
pub fn filter(&self, word: &str) -> Result<Snippets> {
let names: HashMap<String, String> = self
.clone()
.snippets
Expand Down

0 comments on commit 509c89f

Please sign in to comment.