Cargo format

This commit is contained in:
Gregory Schier
2025-01-11 13:53:30 -08:00
parent 295aea4f2e
commit ba330047ca
17 changed files with 82 additions and 163 deletions

View File

@@ -5,7 +5,10 @@ use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use tauri::{Manager, Runtime, WebviewWindow};
use ts_rs::TS;
use yaak_models::queries::{generate_id, get_key_value_int, get_key_value_string, get_or_create_settings, set_key_value_int, set_key_value_string, UpdateSource};
use yaak_models::queries::{
generate_id, get_key_value_int, get_key_value_string, get_or_create_settings,
set_key_value_int, set_key_value_string, UpdateSource,
};
use crate::is_dev;

View File

@@ -74,10 +74,7 @@ impl YaakNotifier {
return Ok(());
}
let notification = resp
.json::<YaakNotification>()
.await
.map_err(|e| e.to_string())?;
let notification = resp.json::<YaakNotification>().await.map_err(|e| e.to_string())?;
let age = notification.timestamp.signed_duration_since(Utc::now());
let seen = get_kv(window).await?;

View File

@@ -1,3 +1,4 @@
use crate::MAIN_WINDOW_PREFIX;
use hex_color::HexColor;
use log::warn;
use objc::{msg_send, sel, sel_impl};
@@ -6,7 +7,6 @@ use tauri::{
plugin::{Builder, TauriPlugin},
Emitter, Listener, Manager, Runtime, Window, WindowEvent,
};
use crate::MAIN_WINDOW_PREFIX;
const WINDOW_CONTROL_PAD_X: f64 = 13.0;
const WINDOW_CONTROL_PAD_Y: f64 = 18.0;
@@ -202,10 +202,9 @@ pub fn setup_traffic_light_positioner<R: Runtime>(window: &Window<R>) {
}
unsafe {
let ns_win = window
.ns_window()
.expect("NS Window should exist to mount traffic light delegate.")
as id;
let ns_win =
window.ns_window().expect("NS Window should exist to mount traffic light delegate.")
as id;
let current_delegate: id = ns_win.delegate();
@@ -322,10 +321,7 @@ pub fn setup_traffic_light_positioner<R: Runtime>(window: &Window<R>) {
) {
unsafe {
with_window_state(&*this, |state: &mut WindowState<R>| {
state
.window
.emit("did-enter-fullscreen", ())
.expect("Failed to emit event");
state.window.emit("did-enter-fullscreen", ()).expect("Failed to emit event");
});
let super_del: id = *this.get_ivar("super_delegate");
@@ -339,10 +335,7 @@ pub fn setup_traffic_light_positioner<R: Runtime>(window: &Window<R>) {
) {
unsafe {
with_window_state(&*this, |state: &mut WindowState<R>| {
state
.window
.emit("will-enter-fullscreen", ())
.expect("Failed to emit event");
state.window.emit("will-enter-fullscreen", ()).expect("Failed to emit event");
});
let super_del: id = *this.get_ivar("super_delegate");
@@ -356,10 +349,7 @@ pub fn setup_traffic_light_positioner<R: Runtime>(window: &Window<R>) {
) {
unsafe {
with_window_state(&*this, |state: &mut WindowState<R>| {
state
.window
.emit("did-exit-fullscreen", ())
.expect("Failed to emit event");
state.window.emit("did-exit-fullscreen", ()).expect("Failed to emit event");
let id = state.window.ns_window().expect("Failed to emit event") as id;
position_traffic_lights(
@@ -381,10 +371,7 @@ pub fn setup_traffic_light_positioner<R: Runtime>(window: &Window<R>) {
) {
unsafe {
with_window_state(&*this, |state: &mut WindowState<R>| {
state
.window
.emit("will-exit-fullscreen", ())
.expect("Failed to emit event");
state.window.emit("will-exit-fullscreen", ()).expect("Failed to emit event");
});
let super_del: id = *this.get_ivar("super_delegate");
@@ -432,11 +419,8 @@ pub fn setup_traffic_light_positioner<R: Runtime>(window: &Window<R>) {
window: window.clone(),
};
let app_box = Box::into_raw(Box::new(app_state)) as *mut c_void;
let random_str: String = rand::thread_rng()
.sample_iter(&Alphanumeric)
.take(20)
.map(char::from)
.collect();
let random_str: String =
rand::thread_rng().sample_iter(&Alphanumeric).take(20).map(char::from).collect();
// We need to ensure we have a unique delegate name, otherwise we will panic while trying to create a duplicate
// delegate with the same name.

View File

@@ -31,11 +31,7 @@ impl TemplateCallback for PluginTemplateCallback {
let window_context = self.window_context.to_owned();
// The beta named the function `Response` but was changed in stable.
// Keep this here for a while because there's no easy way to migrate
let fn_name = if fn_name == "Response" {
"response"
} else {
fn_name
};
let fn_name = if fn_name == "Response" { "response" } else { fn_name };
let function = self
.plugin_manager

View File

@@ -33,8 +33,7 @@ impl Encoder for DynamicCodec {
type Error = Status;
fn encode(&mut self, item: Self::Item, dst: &mut EncodeBuf<'_>) -> Result<(), Self::Error> {
item.encode(dst)
.expect("buffer is too small to decode this message");
item.encode(dst).expect("buffer is too small to decode this message");
Ok(())
}
}
@@ -45,8 +44,7 @@ impl Decoder for DynamicCodec {
fn decode(&mut self, src: &mut DecodeBuf<'_>) -> Result<Option<Self::Item>, Self::Error> {
let mut msg = DynamicMessage::new(self.0.output());
msg.merge(src)
.map_err(|err| Status::internal(err.to_string()))?;
msg.merge(src).map_err(|err| Status::internal(err.to_string()))?;
Ok(Some(msg))
}
}

View File

@@ -30,15 +30,13 @@ pub struct MethodDefinition {
pub server_streaming: bool,
}
static SERIALIZE_OPTIONS: &'static SerializeOptions = &SerializeOptions::new()
.skip_default_fields(false)
.stringify_64_bit_integers(false);
static SERIALIZE_OPTIONS: &'static SerializeOptions =
&SerializeOptions::new().skip_default_fields(false).stringify_64_bit_integers(false);
pub fn serialize_message(msg: &DynamicMessage) -> Result<String, String> {
let mut buf = Vec::new();
let mut se = serde_json::Serializer::pretty(&mut buf);
msg.serialize_with_options(&mut se, SERIALIZE_OPTIONS)
.map_err(|e| e.to_string())?;
msg.serialize_with_options(&mut se, SERIALIZE_OPTIONS).map_err(|e| e.to_string())?;
let s = String::from_utf8(buf).expect("serde_json to emit valid utf8");
Ok(s)
}

View File

@@ -54,19 +54,14 @@ impl From<Status> for StreamError {
impl GrpcConnection {
pub fn service(&self, service: &str) -> Result<ServiceDescriptor, String> {
let service = self
.pool
.get_service_by_name(service)
.ok_or("Failed to find service")?;
let service = self.pool.get_service_by_name(service).ok_or("Failed to find service")?;
Ok(service)
}
pub fn method(&self, service: &str, method: &str) -> Result<MethodDescriptor, String> {
let service = self.service(service)?;
let method = service
.methods()
.find(|m| m.name() == method)
.ok_or("Failed to find method")?;
let method =
service.methods().find(|m| m.name() == method).ok_or("Failed to find method")?;
Ok(method)
}
@@ -132,13 +127,10 @@ impl GrpcConnection {
let path = method_desc_to_path(method);
let codec = DynamicCodec::new(method.clone());
client.ready().await.unwrap();
client
.client_streaming(req, path, codec)
.await
.map_err(|e| StreamError {
message: e.message().to_string(),
status: Some(e),
})
client.client_streaming(req, path, codec).await.map_err(|e| StreamError {
message: e.message().to_string(),
status: Some(e),
})
}
pub async fn server_streaming(
@@ -197,8 +189,7 @@ impl GrpcHandle {
fill_pool_from_files(&self.app_handle, proto_files).await
}?;
self.pools
.insert(make_pool_key(id, uri, proto_files), pool.clone());
self.pools.insert(make_pool_key(id, uri, proto_files), pool.clone());
Ok(())
}
@@ -211,9 +202,7 @@ impl GrpcHandle {
// Ensure reflection is up-to-date
self.reflect(id, uri, proto_files).await?;
let pool = self
.get_pool(id, uri, proto_files)
.ok_or("Failed to get pool".to_string())?;
let pool = self.get_pool(id, uri, proto_files).ok_or("Failed to get pool".to_string())?;
Ok(self.services_from_pool(&pool))
}
@@ -234,7 +223,7 @@ impl GrpcHandle {
&pool,
input_message,
))
.unwrap(),
.unwrap(),
})
}
def
@@ -249,9 +238,7 @@ impl GrpcHandle {
proto_files: &Vec<PathBuf>,
) -> Result<GrpcConnection, String> {
self.reflect(id, uri, proto_files).await?;
let pool = self
.get_pool(id, uri, proto_files)
.ok_or("Failed to get pool")?;
let pool = self.get_pool(id, uri, proto_files).ok_or("Failed to get pool")?;
let uri = uri_from_str(uri)?;
let conn = get_transport();
@@ -301,4 +288,4 @@ fn make_pool_key(id: &str, uri: &str, proto_files: &Vec<PathBuf>) -> String {
);
format!("{:x}", md5::compute(pool_key))
}
}

View File

@@ -104,7 +104,7 @@ pub async fn fill_pool_from_reflection(uri: &Uri) -> Result<DescriptorPool, Stri
if service == "grpc.reflection.v1alpha.ServerReflection" {
continue;
}
if service == "grpc.reflection.v1.ServerReflection"{
if service == "grpc.reflection.v1.ServerReflection" {
// TODO: update reflection client to use v1
continue;
}
@@ -316,8 +316,8 @@ mod topology {
zero_indegree.push(node.clone());
}
}
for (node, deps) in data.out_graph.iter(){
if deps.is_empty(){
for (node, deps) in data.out_graph.iter() {
if deps.is_empty() {
zero_indegree.push(node.clone());
}
}
@@ -344,8 +344,8 @@ mod topology {
}
let node = self.zero_indegree.pop().unwrap();
if let Some(parents) = self.data.in_graph.get(&node){
for parent in parents.iter(){
if let Some(parents) = self.data.in_graph.get(&node) {
for parent in parents.iter() {
let deps = self.data.out_graph.get_mut(parent).unwrap();
deps.remove(&node);
if deps.is_empty() {
@@ -360,7 +360,7 @@ mod topology {
}
#[test]
fn test_sort(){
fn test_sort() {
{
let mut topo_sort = SimpleTopoSort::new();
topo_sort.insert("a", []);
@@ -390,5 +390,4 @@ mod topology {
assert_eq!(iter.next(), None);
}
}
}

View File

@@ -115,7 +115,9 @@ pub async fn check_license<R: Runtime>(app_handle: &AppHandle<R>) -> Result<Lice
match (has_activation_id, trial_period_active) {
(false, true) => Ok(LicenseCheckStatus::Trialing { end: trial_end }),
(false, false) => Ok(LicenseCheckStatus::PersonalUse { trial_ended: trial_end }),
(false, false) => Ok(LicenseCheckStatus::PersonalUse {
trial_ended: trial_end,
}),
(true, _) => {
info!("Checking license activation");
// A license has been activated, so let's check the license server

View File

@@ -1,5 +1,5 @@
pub mod error;
pub mod models;
pub mod queries;
pub mod error;
pub mod plugin;
pub mod plugin;

View File

@@ -1,37 +1,37 @@
use crate::server::plugin_runtime::EventStreamEvent;
use thiserror::Error;
use tokio::io;
use tokio::sync::mpsc::error::SendError;
use crate::server::plugin_runtime::EventStreamEvent;
#[derive(Error, Debug)]
pub enum Error {
#[error("IO error: {0}")]
IoErr(#[from] io::Error),
#[error("Tauri error: {0}")]
TauriErr(#[from] tauri::Error),
#[error("Tauri shell error: {0}")]
TauriShellErr(#[from] tauri_plugin_shell::Error),
#[error("Grpc transport error: {0}")]
GrpcTransportErr(#[from] tonic::transport::Error),
#[error("Grpc send error: {0}")]
GrpcSendErr(#[from] SendError<tonic::Result<EventStreamEvent>>),
#[error("JSON error: {0}")]
JsonErr(#[from] serde_json::Error),
#[error("Plugin not found: {0}")]
PluginNotFoundErr(String),
#[error("Plugin error: {0}")]
PluginErr(String),
#[error("Client not initialized error")]
ClientNotInitializedErr,
#[error("Unknown event received")]
UnknownEventErr,
}

View File

@@ -1,15 +1,15 @@
use std::process::exit;
use crate::manager::PluginManager;
use log::info;
use std::process::exit;
use tauri::plugin::{Builder, TauriPlugin};
use tauri::{Manager, RunEvent, Runtime, State};
use crate::manager::PluginManager;
pub mod error;
pub mod events;
pub mod manager;
mod nodejs;
mod server;
pub mod plugin_handle;
mod server;
mod util;
pub fn init<R: Runtime>() -> TauriPlugin<R> {

View File

@@ -1,8 +1,8 @@
use std::net::SocketAddr;
use crate::error::Result;
use log::info;
use serde;
use serde::Deserialize;
use std::net::SocketAddr;
use tauri::path::BaseDirectory;
use tauri::{AppHandle, Manager, Runtime};
use tauri_plugin_shell::process::CommandEvent;
@@ -20,15 +20,12 @@ pub async fn start_nodejs_plugin_runtime<R: Runtime>(
addr: SocketAddr,
kill_rx: &Receiver<bool>,
) -> Result<()> {
let plugin_runtime_main = app
.path()
.resolve("vendored/plugin-runtime", BaseDirectory::Resource)?
.join("index.cjs");
let plugin_runtime_main =
app.path().resolve("vendored/plugin-runtime", BaseDirectory::Resource)?.join("index.cjs");
// HACK: Remove UNC prefix for Windows paths to pass to sidecar
let plugin_runtime_main = dunce::simplified(plugin_runtime_main.as_path())
.to_string_lossy()
.to_string();
let plugin_runtime_main =
dunce::simplified(plugin_runtime_main.as_path()).to_string_lossy().to_string();
info!("Starting plugin runtime main={}", plugin_runtime_main);
@@ -59,10 +56,7 @@ pub async fn start_nodejs_plugin_runtime<R: Runtime>(
// Check on child
tokio::spawn(async move {
kill_rx
.wait_for(|b| *b == true)
.await
.expect("Kill channel errored");
kill_rx.wait_for(|b| *b == true).await.expect("Kill channel errored");
info!("Killing plugin runtime");
child.kill().expect("Failed to kill plugin runtime");
info!("Killed plugin runtime");

View File

@@ -57,11 +57,8 @@ impl PluginHandle {
pub async fn terminate(&self, window_context: WindowContext) -> Result<()> {
info!("Terminating plugin {}", self.dir);
let event = self.build_event_to_send(
window_context,
&InternalEventPayload::TerminateRequest,
None,
);
let event =
self.build_event_to_send(window_context, &InternalEventPayload::TerminateRequest, None);
self.send(&event).await
}

View File

@@ -1,6 +1,6 @@
pub mod format;
pub mod parser;
pub mod renderer;
pub mod format;
pub use parser::*;
pub use renderer::*;
pub use renderer::*;

View File

@@ -3,25 +3,20 @@ use std::fmt::Display;
use ts_rs::TS;
#[derive(Clone, PartialEq, Debug, Serialize, Deserialize, TS)]
#[ts(export, export_to="parser.ts")]
#[ts(export, export_to = "parser.ts")]
pub struct Tokens {
pub tokens: Vec<Token>,
}
impl Display for Tokens {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let str = self
.tokens
.iter()
.map(|t| t.to_string())
.collect::<Vec<String>>()
.join("");
let str = self.tokens.iter().map(|t| t.to_string()).collect::<Vec<String>>().join("");
write!(f, "{}", str)
}
}
#[derive(Clone, PartialEq, Debug, Serialize, Deserialize, TS)]
#[ts(export, export_to="parser.ts")]
#[ts(export, export_to = "parser.ts")]
pub struct FnArg {
pub name: String,
pub value: Val,
@@ -36,7 +31,7 @@ impl Display for FnArg {
#[derive(Clone, PartialEq, Debug, Serialize, Deserialize, TS)]
#[serde(rename_all = "snake_case", tag = "type")]
#[ts(export, export_to="parser.ts")]
#[ts(export, export_to = "parser.ts")]
pub enum Val {
Str { text: String },
Var { name: String },
@@ -71,7 +66,7 @@ impl Display for Val {
#[derive(Clone, PartialEq, Debug, Serialize, Deserialize, TS)]
#[serde(rename_all = "snake_case", tag = "type")]
#[ts(export, export_to="parser.ts")]
#[ts(export, export_to = "parser.ts")]
pub enum Token {
Raw { text: String },
Tag { val: Val },
@@ -396,9 +391,7 @@ impl Parser {
return false;
}
let cmp = self.chars[self.pos..self.pos + value.len()]
.iter()
.collect::<String>();
let cmp = self.chars[self.pos..self.pos + value.len()].iter().collect::<String>();
if cmp == value {
// We have a match, so advance the current index

View File

@@ -80,10 +80,7 @@ async fn render_tag<T: TemplateCallback>(
match cb.run(name.as_str(), resolved_args.clone()).await {
Ok(s) => s,
Err(e) => {
warn!(
"Failed to run template callback {}({:?}): {}",
name, resolved_args, e
);
warn!("Failed to run template callback {}({:?}): {}", name, resolved_args, e);
"".to_string()
}
}
@@ -116,10 +113,7 @@ mod tests {
let template = "";
let vars = HashMap::new();
let result = "";
assert_eq!(
parse_and_render(template, &vars, &empty_cb).await,
result.to_string()
);
assert_eq!(parse_and_render(template, &vars, &empty_cb).await, result.to_string());
}
#[tokio::test]
@@ -128,10 +122,7 @@ mod tests {
let template = "Hello World!";
let vars = HashMap::new();
let result = "Hello World!";
assert_eq!(
parse_and_render(template, &vars, &empty_cb).await,
result.to_string()
);
assert_eq!(parse_and_render(template, &vars, &empty_cb).await, result.to_string());
}
#[tokio::test]
@@ -140,10 +131,7 @@ mod tests {
let template = "${[ foo ]}";
let vars = HashMap::from([("foo".to_string(), "bar".to_string())]);
let result = "bar";
assert_eq!(
parse_and_render(template, &vars, &empty_cb).await,
result.to_string()
);
assert_eq!(parse_and_render(template, &vars, &empty_cb).await, result.to_string());
}
#[tokio::test]
@@ -156,10 +144,7 @@ mod tests {
vars.insert("baz".to_string(), "baz".to_string());
let result = "foo: bar: baz";
assert_eq!(
parse_and_render(template, &vars, &empty_cb).await,
result.to_string()
);
assert_eq!(parse_and_render(template, &vars, &empty_cb).await, result.to_string());
}
#[tokio::test]
@@ -168,10 +153,7 @@ mod tests {
let template = "hello ${[ word ]} world!";
let vars = HashMap::from([("word".to_string(), "cruel".to_string())]);
let result = "hello cruel world!";
assert_eq!(
parse_and_render(template, &vars, &empty_cb).await,
result.to_string()
);
assert_eq!(parse_and_render(template, &vars, &empty_cb).await, result.to_string());
}
#[tokio::test]
@@ -187,12 +169,7 @@ mod tests {
fn_name: &str,
args: HashMap<String, String>,
) -> Result<String, String> {
Ok(format!(
"{fn_name}: {}, {:?} {:?}",
args.len(),
args.get("a"),
args.get("b")
))
Ok(format!("{fn_name}: {}, {:?} {:?}", args.len(), args.get("a"), args.get("b")))
}
}
assert_eq!(parse_and_render(template, &vars, &CB {}).await, result);
@@ -218,10 +195,7 @@ mod tests {
}
}
assert_eq!(
parse_and_render(template, &vars, &CB {}).await,
result.to_string()
);
assert_eq!(parse_and_render(template, &vars, &CB {}).await, result.to_string());
}
#[tokio::test]
@@ -241,9 +215,6 @@ mod tests {
}
}
assert_eq!(
parse_and_render(template, &vars, &CB {}).await,
result.to_string()
);
assert_eq!(parse_and_render(template, &vars, &CB {}).await, result.to_string());
}
}