From b11cc71f0028ed91aa75cedbd3ce7b2ecb98b2d3 Mon Sep 17 00:00:00 2001 From: Jamie Pine <32987599+jamiepine@users.noreply.github.com> Date: Sun, 13 Mar 2022 09:54:58 -0700 Subject: [PATCH] return types working on useBridgeQuery - added implimentation of SysGetLocation --- apps/desktop/src-tauri/Cargo.lock | Bin 214175 -> 214191 bytes apps/desktop/src-tauri/Cargo.toml | 1 + apps/desktop/src-tauri/src/commands.rs | 19 +- apps/desktop/src-tauri/src/config.rs | 29 -- apps/desktop/src-tauri/src/main.rs | 29 +- apps/desktop/src/components/file/Sidebar.tsx | 1 - packages/core/.rustfmt.toml | 1 + packages/core/bindings/ClientCommand.ts | 2 + packages/core/bindings/ClientQuery.ts | 2 +- packages/core/bindings/CoreEvent.ts | 4 + packages/core/bindings/CoreResource.ts | 2 + packages/core/bindings/CoreResponse.ts | 4 + packages/core/index.ts | 4 + packages/core/src/client/mod.rs | 12 +- packages/core/src/db/migrate.rs | 12 +- packages/core/src/db/mod.rs | 6 +- packages/core/src/file/indexer.rs | 65 +-- packages/core/src/file/retrieve.rs | 13 +- packages/core/src/file/thumb.rs | 3 +- packages/core/src/lib.rs | 41 +- packages/core/src/prisma.rs | 471 ++++--------------- packages/core/src/state/client.rs | 6 +- packages/core/src/sys/locations.rs | 70 +-- packages/core/src/sys/mod.rs | 10 + packages/core/src/sys/volumes.rs | 11 +- packages/core/src/util/time.rs | 16 +- packages/state/lib/bridge.ts | 31 +- 27 files changed, 257 insertions(+), 608 deletions(-) delete mode 100644 apps/desktop/src-tauri/src/config.rs create mode 100644 packages/core/.rustfmt.toml create mode 100644 packages/core/bindings/ClientCommand.ts create mode 100644 packages/core/bindings/CoreEvent.ts create mode 100644 packages/core/bindings/CoreResource.ts create mode 100644 packages/core/bindings/CoreResponse.ts diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index b66fe60c78a6f84ab32aa4b4a4eb466a90f87788..e4260459ad01b4053d78e8c562354e3c95b5d3d4 100644 GIT binary patch delta 29 lcmbQ=$-BOjx1oh`3zJIw^n0;P0@LUJVPfB|-Og097XYr73!DG| delta 19 acmZ4A$veN3x1oh`3zJIwc9V9d>b(F=1qY1) diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 9cdee6d5a..f49d2eee1 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -37,6 +37,7 @@ once_cell = "1.8.0" int-enum = "0.4.0" async-std = "1.10.0" tokio = { version = "1.17.0", features = ["sync"] } +lazy_static = "1.4.0" [features] default = [ "custom-protocol" ] diff --git a/apps/desktop/src-tauri/src/commands.rs b/apps/desktop/src-tauri/src/commands.rs index 18a2cc0e2..c07c19240 100644 --- a/apps/desktop/src-tauri/src/commands.rs +++ b/apps/desktop/src-tauri/src/commands.rs @@ -1,28 +1,11 @@ +// DEPRECATE EVERYTHING IN THIS FILE use anyhow::Result; use sdcorelib::{ file::{indexer, retrieve, retrieve::Directory, watcher::watch_dir}, state::{client, client::ClientState}, sys, sys::{volumes, volumes::Volume}, - ClientCommand, ClientQuery, Core, CoreResponse, }; - -// #[tauri::command(async)] -// pub async fn client_query_transport(data: ClientQuery) -> Result { -// match Core::query(data).await { -// Ok(response) => Ok(response), -// Err(err) => Err(err.to_string()), -// } -// } - -// #[tauri::command(async)] -// pub async fn client_command_transport(data: ClientCommand) -> Result { -// match Core::command(data).await { -// Ok(response) => Ok(response), -// Err(err) => Err(err.to_string()), -// } -// } - #[tauri::command(async)] pub async fn scan_dir(path: String) -> Result<(), String> { let files = indexer::scan(&path).await.map_err(|e| e.to_string()); diff --git a/apps/desktop/src-tauri/src/config.rs b/apps/desktop/src-tauri/src/config.rs deleted file mode 100644 index d6f2181c7..000000000 --- a/apps/desktop/src-tauri/src/config.rs +++ /dev/null @@ -1,29 +0,0 @@ -use serde::Serialize; -use std::fs; -use tauri::api::path; - -#[derive(Serialize)] -pub struct AppConfig { - pub primary_db: std::path::PathBuf, - pub data_dir: std::path::PathBuf, - pub file_type_thumb_dir: std::path::PathBuf, -} - -// returns the app config struct with complete values -pub fn get_config() -> AppConfig { - let app_name = "Spacedrive"; - let data_dir = path::data_dir() - .unwrap_or(std::path::PathBuf::from("./")) - .join(app_name); - let file_type_thumb_dir = data_dir.join("file_icons"); - - // create the data directory if not exists - fs::create_dir_all(&data_dir).unwrap(); - fs::create_dir_all(&file_type_thumb_dir).unwrap(); - - AppConfig { - primary_db: data_dir.join("primary.db3"), - data_dir, - file_type_thumb_dir, - } -} diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs index 5a0884347..4684e1dfb 100644 --- a/apps/desktop/src-tauri/src/main.rs +++ b/apps/desktop/src-tauri/src/main.rs @@ -1,25 +1,27 @@ -use once_cell::sync::OnceCell; use sdcorelib::{ClientCommand, ClientQuery, Core, CoreResponse}; use tauri::api::path; use tauri::Manager; // use tauri_plugin_shadows::Shadows; - mod commands; mod menu; -pub static CORE: OnceCell = OnceCell::new(); - #[tauri::command(async)] -async fn client_query_transport(data: ClientQuery) -> Result { - match CORE.get().unwrap().query(data).await { +async fn client_query_transport( + core: tauri::State<'_, Core>, + data: ClientQuery, +) -> Result { + match core.query(data).await { Ok(response) => Ok(response), Err(err) => Err(err.to_string()), } } #[tauri::command(async)] -async fn client_command_transport(data: ClientCommand) -> Result { - match CORE.get().unwrap().command(data).await { +async fn client_command_transport( + core: tauri::State<'_, Core>, + data: ClientCommand, +) -> Result { + match core.command(data).await { Ok(response) => Ok(response), Err(err) => Err(err.to_string()), } @@ -28,15 +30,15 @@ async fn client_command_transport(data: ClientCommand) -> Result = (props) => {
Locations - {/* @ts-ignore */} {volumes?.map((location, index) => { return (
diff --git a/packages/core/.rustfmt.toml b/packages/core/.rustfmt.toml new file mode 100644 index 000000000..0a4312322 --- /dev/null +++ b/packages/core/.rustfmt.toml @@ -0,0 +1 @@ +max_width = 150 \ No newline at end of file diff --git a/packages/core/bindings/ClientCommand.ts b/packages/core/bindings/ClientCommand.ts new file mode 100644 index 000000000..a20e600b4 --- /dev/null +++ b/packages/core/bindings/ClientCommand.ts @@ -0,0 +1,2 @@ + +export type ClientCommand = { key: "LocScanFull", params: { location_id: bigint, } } | { key: "FileScanQuick", params: { file_id: bigint, } } | { key: "FileScanFull", params: { file_id: bigint, } } | { key: "FileDelete", params: { file_id: bigint, } } | { key: "TagCreate", params: { name: string, color: string, } } | { key: "TagAssign", params: { file_id: bigint, tag_id: bigint, } } | { key: "TagDelete", params: { tag_id: bigint, } } | { key: "LocDelete", params: { location_id: bigint, } } | { key: "LibDelete", params: { library_id: bigint, } } | { key: "SysVolumeUnmount", params: { volume_id: bigint, } }; \ No newline at end of file diff --git a/packages/core/bindings/ClientQuery.ts b/packages/core/bindings/ClientQuery.ts index 2fb84b5a4..00a9e7164 100644 --- a/packages/core/bindings/ClientQuery.ts +++ b/packages/core/bindings/ClientQuery.ts @@ -1,2 +1,2 @@ -export type ClientQuery = { key: "SysGetVolumes" } | { key: "ClientGetCurrent" } | { key: "SysGetLocations", params: { id: string, } } | { key: "LibGetExplorerDir", params: { path: string, limit: number, } }; \ No newline at end of file +export type ClientQuery = { key: "ClientGetState" } | { key: "SysGetVolumes" } | { key: "SysGetLocation", params: { id: bigint, } } | { key: "LibGetExplorerDir", params: { path: string, limit: bigint, } }; \ No newline at end of file diff --git a/packages/core/bindings/CoreEvent.ts b/packages/core/bindings/CoreEvent.ts new file mode 100644 index 000000000..59454a6bf --- /dev/null +++ b/packages/core/bindings/CoreEvent.ts @@ -0,0 +1,4 @@ +import type { ClientQuery } from "./ClientQuery"; +import type { CoreResource } from "./CoreResource"; + +export type CoreEvent = { key: "InvalidateQuery", payload: ClientQuery } | { key: "InvalidateResource", payload: CoreResource } | { key: "Log", payload: { message: string, } } | { key: "DatabaseDisconnected", payload: { reason: string | null, } }; \ No newline at end of file diff --git a/packages/core/bindings/CoreResource.ts b/packages/core/bindings/CoreResource.ts new file mode 100644 index 000000000..f7e0a4969 --- /dev/null +++ b/packages/core/bindings/CoreResource.ts @@ -0,0 +1,2 @@ + +export type CoreResource = "Client" | "Library" | "Location" | "File" | "Job" | "Tag"; \ No newline at end of file diff --git a/packages/core/bindings/CoreResponse.ts b/packages/core/bindings/CoreResponse.ts new file mode 100644 index 000000000..e3d962121 --- /dev/null +++ b/packages/core/bindings/CoreResponse.ts @@ -0,0 +1,4 @@ +import type { LocationResource } from "./LocationResource"; +import type { Volume } from "./Volume"; + +export type CoreResponse = { key: "Success" } | { key: "SysGetVolumes", data: Array } | { key: "SysGetLocations", data: LocationResource }; \ No newline at end of file diff --git a/packages/core/index.ts b/packages/core/index.ts index 9c8e20f8e..12fbf654c 100644 --- a/packages/core/index.ts +++ b/packages/core/index.ts @@ -1,4 +1,8 @@ +export * from './bindings/ClientCommand'; export * from './bindings/ClientEvent'; export * from './bindings/ClientQuery'; export * from './bindings/ClientResponse'; +export * from './bindings/CoreEvent'; +export * from './bindings/CoreResource'; +export * from './bindings/CoreResponse'; export * from './bindings/Volume'; diff --git a/packages/core/src/client/mod.rs b/packages/core/src/client/mod.rs index 390cf5d75..8347f0ce5 100644 --- a/packages/core/src/client/mod.rs +++ b/packages/core/src/client/mod.rs @@ -29,22 +29,14 @@ pub async fn create() -> Result<()> { _ => Platform::Unknown, }; - let client = match db - .client() - .find_unique(Client::uuid().equals(config.client_id.clone())) - .exec() - .await - { + let client = match db.client().find_unique(Client::uuid().equals(config.client_id.clone())).exec().await { Some(client) => client, None => { db.client() .create_one( Client::uuid().set(config.client_id.clone()), Client::name().set(hostname.clone()), - vec![ - Client::platform().set(platform as i64), - Client::online().set(true), - ], + vec![Client::platform().set(platform as i64), Client::online().set(true)], ) .exec() .await diff --git a/packages/core/src/db/migrate.rs b/packages/core/src/db/migrate.rs index 42c70ae29..64dc7ce0a 100644 --- a/packages/core/src/db/migrate.rs +++ b/packages/core/src/db/migrate.rs @@ -13,9 +13,7 @@ pub async fn run_migrations(db_url: &str) -> Result<()> { let client = prisma::new_client_with_url(&format!("file:{}", &db_url)).await; match client - ._query_raw::( - "SELECT name FROM sqlite_master WHERE type='table' AND name='_migrations'", - ) + ._query_raw::("SELECT name FROM sqlite_master WHERE type='table' AND name='_migrations'") .await { Ok(data) => { @@ -30,9 +28,7 @@ pub async fn run_migrations(db_url: &str) -> Result<()> { }; let value: Vec = client - ._query_raw( - "SELECT name FROM sqlite_master WHERE type='table' AND name='_migrations'", - ) + ._query_raw("SELECT name FROM sqlite_master WHERE type='table' AND name='_migrations'") .await .unwrap(); @@ -64,9 +60,7 @@ pub async fn run_migrations(db_url: &str) -> Result<()> { for subdir in migration_subdirs { println!("{:?}", subdir.path()); - let migration_file = subdir - .get_file(subdir.path().join("./migration.sql")) - .unwrap(); + let migration_file = subdir.get_file(subdir.path().join("./migration.sql")).unwrap(); let migration_sql = migration_file.contents_utf8().unwrap(); let digest = sha256_digest(BufReader::new(migration_file.contents()))?; diff --git a/packages/core/src/db/mod.rs b/packages/core/src/db/mod.rs index afe92a587..00b347609 100644 --- a/packages/core/src/db/mod.rs +++ b/packages/core/src/db/mod.rs @@ -10,11 +10,7 @@ pub async fn get() -> Result<&'static PrismaClient, String> { if DB.get().is_none() { let config = state::client::get(); - let current_library = config - .libraries - .iter() - .find(|l| l.library_id == config.current_library_id) - .unwrap(); + let current_library = config.libraries.iter().find(|l| l.library_id == config.current_library_id).unwrap(); let path = current_library.library_path.clone(); // TODO: Error handling when brendan adds it to prisma-client-rust diff --git a/packages/core/src/file/indexer.rs b/packages/core/src/file/indexer.rs index f7d8305f6..e0d3fd3e9 100644 --- a/packages/core/src/file/indexer.rs +++ b/packages/core/src/file/indexer.rs @@ -6,8 +6,7 @@ use walkdir::{DirEntry, WalkDir}; use super::watcher::watch_dir; use crate::db; -use crate::prisma::LocationData; -use crate::sys::locations::{create_location, get_location}; +use crate::sys::locations::{create_location, get_location, LocationResource}; use crate::util::time; pub async fn scan_paths(location_id: i64) -> Result<()> { @@ -54,8 +53,7 @@ pub async fn scan(path: &str) -> Result<()> { let scan_start = Instant::now(); // walk through directory recursively for entry in WalkDir::new(path).into_iter().filter_entry(|dir| { - let approved = - !is_hidden(dir) && !is_app_bundle(dir) && !is_node_modules(dir) && !is_library(dir); + let approved = !is_hidden(dir) && !is_app_bundle(dir) && !is_node_modules(dir) && !is_library(dir); approved }) { // extract directory entry or log and continue if failed @@ -68,11 +66,7 @@ pub async fn scan(path: &str) -> Result<()> { }; let path = entry.path(); - let parent_path = path - .parent() - .unwrap_or(Path::new("")) - .to_str() - .unwrap_or(""); + let parent_path = path.parent().unwrap_or(Path::new("")).to_str().unwrap_or(""); let parent_dir_id = dirs.get(&*parent_path); println!("Discovered: {:?}, {:?}", &path, &parent_dir_id); @@ -95,15 +89,13 @@ pub async fn scan(path: &str) -> Result<()> { // vector to store active models let mut files: Vec = Vec::new(); for (file_path, file_id, parent_dir_id) in chunk { - files.push( - match prepare_model(&file_path, *file_id, &location, parent_dir_id) { - Ok(file) => file, - Err(e) => { - println!("Error creating file model from path {:?}: {}", file_path, e); - continue; - } - }, - ); + files.push(match prepare_model(&file_path, *file_id, &location, parent_dir_id) { + Ok(file) => file, + Err(e) => { + println!("Error creating file model from path {:?}: {}", file_path, e); + continue; + } + }); } let raw_sql = format!( r#" @@ -126,12 +118,7 @@ pub async fn scan(path: &str) -> Result<()> { } // reads a file at a path and creates an ActiveModel with metadata -fn prepare_model( - file_path: &PathBuf, - id: i64, - location: &LocationData, - parent_id: &Option, -) -> Result { +fn prepare_model(file_path: &PathBuf, id: i64, location: &LocationResource, parent_id: &Option) -> Result { let metadata = fs::metadata(&file_path)?; let location_path = location.path.as_ref().unwrap().as_str(); let size = metadata.len(); @@ -157,12 +144,8 @@ fn prepare_model( &name, &extension, &size.to_string(), - &time::system_time_to_date_time(metadata.created()) - .unwrap() - .to_string(), - &time::system_time_to_date_time(metadata.modified()) - .unwrap() - .to_string(), + &time::system_time_to_date_time(metadata.created()).unwrap().to_string(), + &time::system_time_to_date_time(metadata.modified()).unwrap().to_string(), )) } @@ -179,19 +162,11 @@ pub async fn test_scan(path: &str) -> Result<()> { // extract name from OsStr returned by PathBuff fn extract_name(os_string: Option<&OsStr>) -> String { - os_string - .unwrap_or_default() - .to_str() - .unwrap_or_default() - .to_owned() + os_string.unwrap_or_default().to_str().unwrap_or_default().to_owned() } fn is_hidden(entry: &DirEntry) -> bool { - entry - .file_name() - .to_str() - .map(|s| s.starts_with(".")) - .unwrap_or(false) + entry.file_name().to_str().map(|s| s.starts_with(".")).unwrap_or(false) } fn is_library(entry: &DirEntry) -> bool { @@ -204,11 +179,7 @@ fn is_library(entry: &DirEntry) -> bool { } fn is_node_modules(entry: &DirEntry) -> bool { - entry - .file_name() - .to_str() - .map(|s| s.contains("node_modules")) - .unwrap_or(false) + entry.file_name().to_str().map(|s| s.contains("node_modules")).unwrap_or(false) } fn is_app_bundle(entry: &DirEntry) -> bool { @@ -247,9 +218,7 @@ fn construct_file_sql( id, is_dir as u8, location_id, - parent_id - .map(|id| id.to_string()) - .unwrap_or("NULL".to_string()), + parent_id.map(|id| id.to_string()).unwrap_or("NULL".to_string()), stem, name, extension, diff --git a/packages/core/src/file/retrieve.rs b/packages/core/src/file/retrieve.rs index 6e274bff7..46cd48ee7 100644 --- a/packages/core/src/file/retrieve.rs +++ b/packages/core/src/file/retrieve.rs @@ -21,21 +21,12 @@ pub async fn get_dir_with_contents(path: &str) -> Result { // meta_integrity_hash.truncate(20); - let directory = match db - .file() - .find_unique(File::name().equals(path.into())) - .exec() - .await - { + let directory = match db.file().find_unique(File::name().equals(path.into())).exec().await { Some(file) => file, None => return Err("directory_not_found".to_owned()), }; - let files = db - .file() - .find_many(vec![File::parent_id().equals(directory.id)]) - .exec() - .await; + let files = db.file().find_many(vec![File::parent_id().equals(directory.id)]).exec().await; Ok(Directory { directory: directory.clone(), diff --git a/packages/core/src/file/thumb.rs b/packages/core/src/file/thumb.rs index 225ed637b..71311c0a3 100644 --- a/packages/core/src/file/thumb.rs +++ b/packages/core/src/file/thumb.rs @@ -9,8 +9,7 @@ pub async fn create_thumb(path: &str) -> Result<()> { let file = File::open(path).unwrap(); let reader = BufReader::new(file); - let mut thumbnails = - create_thumbnails(reader, mime::IMAGE_PNG, [ThumbnailSize::Small]).unwrap(); + let mut thumbnails = create_thumbnails(reader, mime::IMAGE_PNG, [ThumbnailSize::Small]).unwrap(); let thumbnail = thumbnails.pop().unwrap(); diff --git a/packages/core/src/lib.rs b/packages/core/src/lib.rs index f89ac81c7..f1b0c3347 100644 --- a/packages/core/src/lib.rs +++ b/packages/core/src/lib.rs @@ -22,13 +22,12 @@ pub mod util; pub struct Core { pub event_sender: mpsc::Sender, - pub event_receiver: mpsc::Receiver, pub state: ClientState, } impl Core { // create new instance of core, run startup tasks - pub async fn new(mut data_dir: std::path::PathBuf) -> Core { + pub async fn new(mut data_dir: std::path::PathBuf) -> (Core, mpsc::Receiver) { let (event_sender, event_receiver) = mpsc::channel(100); data_dir = data_dir.join("spacedrive"); @@ -38,19 +37,13 @@ impl Core { // prepare basic client state let mut state = ClientState::new(data_dir, "diamond-mastering-space-dragon").unwrap(); // load from disk - state - .read_disk() - .unwrap_or(error!("No client state found, creating new one...")); + state.read_disk().unwrap_or(error!("No client state found, creating new one...")); state.save(); - let core = Core { - event_sender, - event_receiver, - state, - }; + let core = Core { event_sender, state }; core.initializer().await; - core + (core, event_receiver) // activate p2p listeners // p2p::listener::listen(None); } @@ -85,7 +78,7 @@ impl Core { info!("Core query: {:?}", query); let response = match query { ClientQuery::SysGetVolumes => CoreResponse::SysGetVolumes(sys::volumes::get()?), - ClientQuery::SysGetLocations { id: _ } => todo!(), + ClientQuery::SysGetLocation { id } => CoreResponse::SysGetLocations(sys::locations::get_location(id).await?), ClientQuery::LibGetExplorerDir { path: _, limit: _ } => todo!(), ClientQuery::ClientGetState => todo!(), }; @@ -102,16 +95,16 @@ impl Core { #[serde(tag = "key", content = "params")] #[ts(export)] pub enum ClientCommand { - LocScanFull { location_id: u32 }, - FileScanQuick { file_id: u32 }, - FileScanFull { file_id: u32 }, - FileDelete { file_id: u32 }, + LocScanFull { location_id: i64 }, + FileScanQuick { file_id: i64 }, + FileScanFull { file_id: i64 }, + FileDelete { file_id: i64 }, TagCreate { name: String, color: String }, - TagAssign { file_id: u32, tag_id: u32 }, - TagDelete { tag_id: u32 }, - LocDelete { location_id: u32 }, - LibDelete { library_id: u32 }, - SysVolumeUnmount { volume_id: u32 }, + TagAssign { file_id: i64, tag_id: i64 }, + TagDelete { tag_id: i64 }, + LocDelete { location_id: i64 }, + LibDelete { library_id: i64 }, + SysVolumeUnmount { volume_id: i64 }, } // represents an event this library can emit @@ -121,8 +114,8 @@ pub enum ClientCommand { pub enum ClientQuery { ClientGetState, SysGetVolumes, - SysGetLocations { id: String }, - LibGetExplorerDir { path: String, limit: u32 }, + SysGetLocation { id: i64 }, + LibGetExplorerDir { path: String, limit: i64 }, } // represents an event this library can emit @@ -133,7 +126,6 @@ pub enum CoreEvent { // most all events should be once of these two InvalidateQuery(ClientQuery), InvalidateResource(CoreResource), - Log { message: String }, DatabaseDisconnected { reason: Option }, } @@ -144,6 +136,7 @@ pub enum CoreEvent { pub enum CoreResponse { Success, SysGetVolumes(Vec), + SysGetLocations(sys::locations::LocationResource), } #[derive(Error, Debug)] diff --git a/packages/core/src/prisma.rs b/packages/core/src/prisma.rs index f9bdb9198..bc7d6d46c 100644 --- a/packages/core/src/prisma.rs +++ b/packages/core/src/prisma.rs @@ -3,9 +3,7 @@ use prisma_client_rust::datamodel::parse_configuration; use prisma_client_rust::prisma_models::InternalDataModelBuilder; use prisma_client_rust::query::*; -use prisma_client_rust::query_core::{ - executor, schema_builder, BuildMode, CoreError, QueryExecutor, QuerySchema, -}; +use prisma_client_rust::query_core::{executor, schema_builder, BuildMode, CoreError, QueryExecutor, QuerySchema}; use prisma_client_rust::{chrono, operator::Operator, serde_json, DeleteResult}; use serde::{Deserialize, Serialize}; use std::path::Path; @@ -17,10 +15,7 @@ pub struct PrismaClient { pub async fn new_client() -> PrismaClient { let datamodel_str = "datasource db {\n provider = \"sqlite\"\n url = \"file:dev.db\"\n}\n\ngenerator client {\n provider = \"prisma-client-rust\"\n output = \"../src/prisma.rs\"\n}\n\ngenerator js {\n provider = \"prisma-client-js\"\n output = \"../types\"\n}\n\nmodel Migration {\n id Int @id @default(autoincrement())\n name String\n checksum String @unique\n steps_applied Int @default(0)\n applied_at DateTime @default(now())\n\n @@map(\"_migrations\")\n}\n\nmodel Library {\n id Int @id @default(autoincrement())\n uuid String @unique\n name String\n remote_id String?\n is_primary Boolean @default(true)\n encryption Int @default(0)\n date_created DateTime @default(now())\n timezone String?\n spaces Space[]\n\n @@map(\"libraries\")\n}\n\nmodel LibraryStatistics {\n id Int @id @default(autoincrement())\n date_captured DateTime @default(now())\n library_id Int @unique\n total_file_count Int @default(0)\n total_bytes_used String @default(\"0\")\n total_byte_capacity String @default(\"0\")\n total_unique_bytes String @default(\"0\")\n\n @@map(\"library_statistics\")\n}\n\nmodel Client {\n id Int @id @default(autoincrement())\n uuid String @unique\n name String\n platform Int @default(0)\n version String?\n online Boolean? @default(true)\n last_seen DateTime @default(now())\n timezone String?\n date_created DateTime @default(now())\n jobs Job[]\n\n @@map(\"clients\")\n}\n\nmodel Location {\n id Int @id @default(autoincrement())\n name String?\n path String?\n total_capacity Int?\n available_capacity Int?\n is_removable Boolean @default(true)\n is_ejectable Boolean @default(true)\n is_root_filesystem Boolean @default(true)\n is_online Boolean @default(true)\n date_created DateTime @default(now())\n files File[]\n\n @@map(\"locations\")\n}\n\nmodel File {\n id Int @id @default(autoincrement())\n is_dir Boolean @default(false)\n location_id Int\n stem String\n name String\n extension String?\n quick_checksum String? // 100 * 100 byte samples\n full_checksum String? // full byte to byte hash\n size_in_bytes String\n encryption Int @default(0)\n date_created DateTime @default(now())\n date_modified DateTime @default(now())\n date_indexed DateTime @default(now())\n ipfs_id String?\n\n location Location? @relation(fields: [location_id], references: [id], onDelete: NoAction, onUpdate: NoAction)\n\n parent File? @relation(\"directory_files\", fields: [parent_id], references: [id])\n parent_id Int?\n children File[] @relation(\"directory_files\")\n\n file_tags TagOnFile[]\n @@unique([location_id, stem, name, extension])\n @@map(\"files\")\n}\n\nmodel Tag {\n id Int @id @default(autoincrement())\n name String?\n encryption Int? @default(0)\n total_files Int? @default(0)\n redundancy_goal Int? @default(1)\n date_created DateTime @default(now())\n date_modified DateTime @default(now())\n\n tag_files TagOnFile[]\n\n @@map(\"tags\")\n}\n\nmodel TagOnFile {\n date_created DateTime @default(now())\n\n tag_id Int\n tag Tag @relation(fields: [tag_id], references: [id], onDelete: NoAction, onUpdate: NoAction)\n\n file_id Int\n file File @relation(fields: [file_id], references: [id], onDelete: NoAction, onUpdate: NoAction)\n\n @@id([tag_id, file_id])\n @@map(\"tags_on_files\")\n}\n\nmodel Job {\n id Int @id @default(autoincrement())\n client_id Int\n action Int\n status Int @default(0)\n percentage_complete Int @default(0)\n task_count Int @default(1)\n completed_task_count Int @default(0)\n date_created DateTime @default(now())\n date_modified DateTime @default(now())\n clients Client @relation(fields: [client_id], references: [id], onDelete: NoAction, onUpdate: NoAction)\n\n @@map(\"jobs\")\n}\n\nmodel Space {\n id Int @id @default(autoincrement())\n name String\n encryption Int? @default(0)\n date_created DateTime @default(now())\n date_modified DateTime @default(now())\n\n Library Library? @relation(fields: [libraryId], references: [id])\n libraryId Int?\n @@map(\"spaces\")\n}\n" ; let config = parse_configuration(datamodel_str).unwrap().subject; - let source = config - .datasources - .first() - .expect("Pleasy supply a datasource in your schema.prisma file"); + let source = config.datasources.first().expect("Pleasy supply a datasource in your schema.prisma file"); let url = if let Some(url) = source.load_shadow_database_url().unwrap() { url } else { @@ -43,10 +38,7 @@ pub async fn new_client() -> PrismaClient { pub async fn new_client_with_url(url: &str) -> PrismaClient { let datamodel_str = "datasource db {\n provider = \"sqlite\"\n url = \"file:dev.db\"\n}\n\ngenerator client {\n provider = \"prisma-client-rust\"\n output = \"../src/prisma.rs\"\n}\n\ngenerator js {\n provider = \"prisma-client-js\"\n output = \"../types\"\n}\n\nmodel Migration {\n id Int @id @default(autoincrement())\n name String\n checksum String @unique\n steps_applied Int @default(0)\n applied_at DateTime @default(now())\n\n @@map(\"_migrations\")\n}\n\nmodel Library {\n id Int @id @default(autoincrement())\n uuid String @unique\n name String\n remote_id String?\n is_primary Boolean @default(true)\n encryption Int @default(0)\n date_created DateTime @default(now())\n timezone String?\n spaces Space[]\n\n @@map(\"libraries\")\n}\n\nmodel LibraryStatistics {\n id Int @id @default(autoincrement())\n date_captured DateTime @default(now())\n library_id Int @unique\n total_file_count Int @default(0)\n total_bytes_used String @default(\"0\")\n total_byte_capacity String @default(\"0\")\n total_unique_bytes String @default(\"0\")\n\n @@map(\"library_statistics\")\n}\n\nmodel Client {\n id Int @id @default(autoincrement())\n uuid String @unique\n name String\n platform Int @default(0)\n version String?\n online Boolean? @default(true)\n last_seen DateTime @default(now())\n timezone String?\n date_created DateTime @default(now())\n jobs Job[]\n\n @@map(\"clients\")\n}\n\nmodel Location {\n id Int @id @default(autoincrement())\n name String?\n path String?\n total_capacity Int?\n available_capacity Int?\n is_removable Boolean @default(true)\n is_ejectable Boolean @default(true)\n is_root_filesystem Boolean @default(true)\n is_online Boolean @default(true)\n date_created DateTime @default(now())\n files File[]\n\n @@map(\"locations\")\n}\n\nmodel File {\n id Int @id @default(autoincrement())\n is_dir Boolean @default(false)\n location_id Int\n stem String\n name String\n extension String?\n quick_checksum String? // 100 * 100 byte samples\n full_checksum String? // full byte to byte hash\n size_in_bytes String\n encryption Int @default(0)\n date_created DateTime @default(now())\n date_modified DateTime @default(now())\n date_indexed DateTime @default(now())\n ipfs_id String?\n\n location Location? @relation(fields: [location_id], references: [id], onDelete: NoAction, onUpdate: NoAction)\n\n parent File? @relation(\"directory_files\", fields: [parent_id], references: [id])\n parent_id Int?\n children File[] @relation(\"directory_files\")\n\n file_tags TagOnFile[]\n @@unique([location_id, stem, name, extension])\n @@map(\"files\")\n}\n\nmodel Tag {\n id Int @id @default(autoincrement())\n name String?\n encryption Int? @default(0)\n total_files Int? @default(0)\n redundancy_goal Int? @default(1)\n date_created DateTime @default(now())\n date_modified DateTime @default(now())\n\n tag_files TagOnFile[]\n\n @@map(\"tags\")\n}\n\nmodel TagOnFile {\n date_created DateTime @default(now())\n\n tag_id Int\n tag Tag @relation(fields: [tag_id], references: [id], onDelete: NoAction, onUpdate: NoAction)\n\n file_id Int\n file File @relation(fields: [file_id], references: [id], onDelete: NoAction, onUpdate: NoAction)\n\n @@id([tag_id, file_id])\n @@map(\"tags_on_files\")\n}\n\nmodel Job {\n id Int @id @default(autoincrement())\n client_id Int\n action Int\n status Int @default(0)\n percentage_complete Int @default(0)\n task_count Int @default(1)\n completed_task_count Int @default(0)\n date_created DateTime @default(now())\n date_modified DateTime @default(now())\n clients Client @relation(fields: [client_id], references: [id], onDelete: NoAction, onUpdate: NoAction)\n\n @@map(\"jobs\")\n}\n\nmodel Space {\n id Int @id @default(autoincrement())\n name String\n encryption Int? @default(0)\n date_created DateTime @default(now())\n date_modified DateTime @default(now())\n\n Library Library? @relation(fields: [libraryId], references: [id])\n libraryId Int?\n @@map(\"spaces\")\n}\n" ; let config = parse_configuration(datamodel_str).unwrap().subject; - let source = config - .datasources - .first() - .expect("Pleasy supply a datasource in your schema.prisma file"); + let source = config.datasources.first().expect("Pleasy supply a datasource in your schema.prisma file"); let (db_name, executor) = executor::load(&source, &[], &url).await.unwrap(); let internal_model = InternalDataModelBuilder::new(&datamodel_str).build(db_name); let query_schema = Arc::new(schema_builder::build( @@ -58,16 +50,10 @@ pub async fn new_client_with_url(url: &str) -> PrismaClient { source.referential_integrity(), )); executor.primary_connector().get_connection().await.unwrap(); - PrismaClient { - executor, - query_schema, - } + PrismaClient { executor, query_schema } } impl PrismaClient { - pub async fn _query_raw( - &self, - query: &str, - ) -> Result, CoreError> { + pub async fn _query_raw(&self, query: &str) -> Result, CoreError> { let query = Query { ctx: QueryContext::new(&self.executor, self.query_schema.clone()), operation: "mutation".into(), @@ -684,10 +670,7 @@ impl<'a> MigrationFindMany<'a> { } } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -700,10 +683,7 @@ impl<'a> MigrationFindFirst<'a> { self.query.perform::>().await.unwrap() } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -754,10 +734,7 @@ impl<'a> MigrationFindUnique<'a> { } } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -778,10 +755,7 @@ impl<'a> MigrationUpdateUnique<'a> { self.query.perform::().await.unwrap() } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -794,10 +768,7 @@ impl<'a> MigrationUpdateMany<'a> { self.query.perform::>().await.unwrap() } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -881,12 +852,7 @@ impl<'a> MigrationActions<'a> { }; MigrationFindMany { query } } - pub fn create_one( - &self, - name: MigrationSetName, - checksum: MigrationSetChecksum, - params: Vec, - ) -> MigrationCreateOne { + pub fn create_one(&self, name: MigrationSetName, checksum: MigrationSetChecksum, params: Vec) -> MigrationCreateOne { let mut input_fields = params.into_iter().map(|p| p.field()).collect::>(); input_fields.push(MigrationSetParam::from(name).field()); input_fields.push(MigrationSetParam::from(checksum).field()); @@ -943,10 +909,7 @@ impl LibraryData { pub fn spaces(&self) -> Result<&Vec, String> { match self.spaces.as_ref() { Some(v) => Ok(v), - None => Err( - "attempted to access spaces but did not fetch it using the .with() syntax" - .to_string(), - ), + None => Err("attempted to access spaces but did not fetch it using the .with() syntax".to_string()), } } } @@ -1667,9 +1630,7 @@ impl LibrarySetParam { name: "spaces".into(), fields: Some(vec![Field { name: "connect".into(), - fields: Some(transform_equals( - where_params.into_iter().map(|item| item.field()).collect(), - )), + fields: Some(transform_equals(where_params.into_iter().map(|item| item.field()).collect())), list: true, wrap_list: true, ..Default::default() @@ -1682,9 +1643,7 @@ impl LibrarySetParam { name: "disconnect".into(), list: true, wrap_list: true, - fields: Some(transform_equals( - where_params.into_iter().map(|item| item.field()).collect(), - )), + fields: Some(transform_equals(where_params.into_iter().map(|item| item.field()).collect())), ..Default::default() }]), ..Default::default() @@ -1739,10 +1698,7 @@ impl<'a> LibraryFindMany<'a> { } } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -1755,10 +1711,7 @@ impl<'a> LibraryFindFirst<'a> { self.query.perform::>().await.unwrap() } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -1809,10 +1762,7 @@ impl<'a> LibraryFindUnique<'a> { } } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -1833,10 +1783,7 @@ impl<'a> LibraryUpdateUnique<'a> { self.query.perform::().await.unwrap() } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -1849,10 +1796,7 @@ impl<'a> LibraryUpdateMany<'a> { self.query.perform::>().await.unwrap() } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -1936,12 +1880,7 @@ impl<'a> LibraryActions<'a> { }; LibraryFindMany { query } } - pub fn create_one( - &self, - uuid: LibrarySetUuid, - name: LibrarySetName, - params: Vec, - ) -> LibraryCreateOne { + pub fn create_one(&self, uuid: LibrarySetUuid, name: LibrarySetName, params: Vec) -> LibraryCreateOne { let mut input_fields = params.into_iter().map(|p| p.field()).collect::>(); input_fields.push(LibrarySetParam::from(uuid).field()); input_fields.push(LibrarySetParam::from(name).field()); @@ -2055,25 +1994,16 @@ impl LibraryStatisticsDateCapturedField { pub fn after(&self, value: chrono::DateTime) -> LibraryStatisticsWhereParam { LibraryStatisticsWhereParam::DateCapturedAfter(value) } - pub fn before_equals( - &self, - value: chrono::DateTime, - ) -> LibraryStatisticsWhereParam { + pub fn before_equals(&self, value: chrono::DateTime) -> LibraryStatisticsWhereParam { LibraryStatisticsWhereParam::DateCapturedBeforeEquals(value) } - pub fn after_equals( - &self, - value: chrono::DateTime, - ) -> LibraryStatisticsWhereParam { + pub fn after_equals(&self, value: chrono::DateTime) -> LibraryStatisticsWhereParam { LibraryStatisticsWhereParam::DateCapturedAfterEquals(value) } pub fn equals(&self, value: chrono::DateTime) -> LibraryStatisticsWhereParam { LibraryStatisticsWhereParam::DateCapturedEquals(value) } - pub fn set>( - &self, - value: chrono::DateTime, - ) -> T { + pub fn set>(&self, value: chrono::DateTime) -> T { LibraryStatisticsSetDateCaptured(value).into() } } @@ -2633,10 +2563,7 @@ pub struct LibraryStatisticsFindMany<'a> { } impl<'a> LibraryStatisticsFindMany<'a> { pub async fn exec(self) -> Vec { - self.query - .perform::>() - .await - .unwrap() + self.query.perform::>().await.unwrap() } pub fn delete(self) -> LibraryStatisticsDelete<'a> { LibraryStatisticsDelete { @@ -2649,10 +2576,7 @@ impl<'a> LibraryStatisticsFindMany<'a> { }, } } - pub fn update( - mut self, - params: Vec, - ) -> LibraryStatisticsUpdateMany<'a> { + pub fn update(mut self, params: Vec) -> LibraryStatisticsUpdateMany<'a> { self.query.inputs.push(Input { name: "data".into(), fields: params @@ -2681,10 +2605,7 @@ impl<'a> LibraryStatisticsFindMany<'a> { } } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -2694,16 +2615,10 @@ pub struct LibraryStatisticsFindFirst<'a> { } impl<'a> LibraryStatisticsFindFirst<'a> { pub async fn exec(self) -> Option { - self.query - .perform::>() - .await - .unwrap() + self.query.perform::>().await.unwrap() } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -2713,10 +2628,7 @@ pub struct LibraryStatisticsFindUnique<'a> { } impl<'a> LibraryStatisticsFindUnique<'a> { pub async fn exec(self) -> Option { - self.query - .perform::>() - .await - .unwrap() + self.query.perform::>().await.unwrap() } pub fn delete(self) -> LibraryStatisticsDelete<'a> { LibraryStatisticsDelete { @@ -2728,10 +2640,7 @@ impl<'a> LibraryStatisticsFindUnique<'a> { }, } } - pub fn update( - mut self, - params: Vec, - ) -> LibraryStatisticsUpdateUnique<'a> { + pub fn update(mut self, params: Vec) -> LibraryStatisticsUpdateUnique<'a> { self.query.inputs.push(Input { name: "data".into(), fields: params @@ -2760,10 +2669,7 @@ impl<'a> LibraryStatisticsFindUnique<'a> { } } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -2784,10 +2690,7 @@ impl<'a> LibraryStatisticsUpdateUnique<'a> { self.query.perform::().await.unwrap() } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -2797,16 +2700,10 @@ pub struct LibraryStatisticsUpdateMany<'a> { } impl<'a> LibraryStatisticsUpdateMany<'a> { pub async fn exec(self) -> Vec { - self.query - .perform::>() - .await - .unwrap() + self.query.perform::>().await.unwrap() } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -2840,10 +2737,7 @@ impl<'a> LibraryStatisticsActions<'a> { }; LibraryStatisticsFindUnique { query } } - pub fn find_first( - &self, - params: Vec, - ) -> LibraryStatisticsFindFirst { + pub fn find_first(&self, params: Vec) -> LibraryStatisticsFindFirst { let where_fields: Vec = params.into_iter().map(|param| param.field()).collect(); let inputs = if where_fields.len() > 0 { vec![Input { @@ -2893,11 +2787,7 @@ impl<'a> LibraryStatisticsActions<'a> { }; LibraryStatisticsFindMany { query } } - pub fn create_one( - &self, - library_id: LibraryStatisticsSetLibraryId, - params: Vec, - ) -> LibraryStatisticsCreateOne { + pub fn create_one(&self, library_id: LibraryStatisticsSetLibraryId, params: Vec) -> LibraryStatisticsCreateOne { let mut input_fields = params.into_iter().map(|p| p.field()).collect::>(); input_fields.push(LibraryStatisticsSetParam::from(library_id).field()); let query = Query { @@ -2956,10 +2846,7 @@ impl ClientData { pub fn jobs(&self) -> Result<&Vec, String> { match self.jobs.as_ref() { Some(v) => Ok(v), - None => Err( - "attempted to access jobs but did not fetch it using the .with() syntax" - .to_string(), - ), + None => Err("attempted to access jobs but did not fetch it using the .with() syntax".to_string()), } } } @@ -3766,9 +3653,7 @@ impl ClientSetParam { name: "jobs".into(), fields: Some(vec![Field { name: "connect".into(), - fields: Some(transform_equals( - where_params.into_iter().map(|item| item.field()).collect(), - )), + fields: Some(transform_equals(where_params.into_iter().map(|item| item.field()).collect())), list: true, wrap_list: true, ..Default::default() @@ -3781,9 +3666,7 @@ impl ClientSetParam { name: "disconnect".into(), list: true, wrap_list: true, - fields: Some(transform_equals( - where_params.into_iter().map(|item| item.field()).collect(), - )), + fields: Some(transform_equals(where_params.into_iter().map(|item| item.field()).collect())), ..Default::default() }]), ..Default::default() @@ -3838,10 +3721,7 @@ impl<'a> ClientFindMany<'a> { } } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -3854,10 +3734,7 @@ impl<'a> ClientFindFirst<'a> { self.query.perform::>().await.unwrap() } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -3908,10 +3785,7 @@ impl<'a> ClientFindUnique<'a> { } } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -3932,10 +3806,7 @@ impl<'a> ClientUpdateUnique<'a> { self.query.perform::().await.unwrap() } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -3948,10 +3819,7 @@ impl<'a> ClientUpdateMany<'a> { self.query.perform::>().await.unwrap() } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -4035,12 +3903,7 @@ impl<'a> ClientActions<'a> { }; ClientFindMany { query } } - pub fn create_one( - &self, - uuid: ClientSetUuid, - name: ClientSetName, - params: Vec, - ) -> ClientCreateOne { + pub fn create_one(&self, uuid: ClientSetUuid, name: ClientSetName, params: Vec) -> ClientCreateOne { let mut input_fields = params.into_iter().map(|p| p.field()).collect::>(); input_fields.push(ClientSetParam::from(uuid).field()); input_fields.push(ClientSetParam::from(name).field()); @@ -4103,10 +3966,7 @@ impl LocationData { pub fn files(&self) -> Result<&Vec, String> { match self.files.as_ref() { Some(v) => Ok(v), - None => Err( - "attempted to access files but did not fetch it using the .with() syntax" - .to_string(), - ), + None => Err("attempted to access files but did not fetch it using the .with() syntax".to_string()), } } } @@ -4869,9 +4729,7 @@ impl LocationSetParam { name: "files".into(), fields: Some(vec![Field { name: "connect".into(), - fields: Some(transform_equals( - where_params.into_iter().map(|item| item.field()).collect(), - )), + fields: Some(transform_equals(where_params.into_iter().map(|item| item.field()).collect())), list: true, wrap_list: true, ..Default::default() @@ -4884,9 +4742,7 @@ impl LocationSetParam { name: "disconnect".into(), list: true, wrap_list: true, - fields: Some(transform_equals( - where_params.into_iter().map(|item| item.field()).collect(), - )), + fields: Some(transform_equals(where_params.into_iter().map(|item| item.field()).collect())), ..Default::default() }]), ..Default::default() @@ -4941,10 +4797,7 @@ impl<'a> LocationFindMany<'a> { } } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -4957,10 +4810,7 @@ impl<'a> LocationFindFirst<'a> { self.query.perform::>().await.unwrap() } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -5011,10 +4861,7 @@ impl<'a> LocationFindUnique<'a> { } } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -5035,10 +4882,7 @@ impl<'a> LocationUpdateUnique<'a> { self.query.perform::().await.unwrap() } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -5051,10 +4895,7 @@ impl<'a> LocationUpdateMany<'a> { self.query.perform::>().await.unwrap() } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -5226,19 +5067,13 @@ impl FileData { pub fn children(&self) -> Result<&Vec, String> { match self.children.as_ref() { Some(v) => Ok(v), - None => Err( - "attempted to access children but did not fetch it using the .with() syntax" - .to_string(), - ), + None => Err("attempted to access children but did not fetch it using the .with() syntax".to_string()), } } pub fn file_tags(&self) -> Result<&Vec, String> { match self.file_tags.as_ref() { Some(v) => Ok(v), - None => Err( - "attempted to access file_tags but did not fetch it using the .with() syntax" - .to_string(), - ), + None => Err("attempted to access file_tags but did not fetch it using the .with() syntax".to_string()), } } } @@ -6706,9 +6541,7 @@ impl FileSetParam { name: "children".into(), fields: Some(vec![Field { name: "connect".into(), - fields: Some(transform_equals( - where_params.into_iter().map(|item| item.field()).collect(), - )), + fields: Some(transform_equals(where_params.into_iter().map(|item| item.field()).collect())), list: true, wrap_list: true, ..Default::default() @@ -6721,9 +6554,7 @@ impl FileSetParam { name: "disconnect".into(), list: true, wrap_list: true, - fields: Some(transform_equals( - where_params.into_iter().map(|item| item.field()).collect(), - )), + fields: Some(transform_equals(where_params.into_iter().map(|item| item.field()).collect())), ..Default::default() }]), ..Default::default() @@ -6732,9 +6563,7 @@ impl FileSetParam { name: "file_tags".into(), fields: Some(vec![Field { name: "connect".into(), - fields: Some(transform_equals( - where_params.into_iter().map(|item| item.field()).collect(), - )), + fields: Some(transform_equals(where_params.into_iter().map(|item| item.field()).collect())), list: true, wrap_list: true, ..Default::default() @@ -6747,9 +6576,7 @@ impl FileSetParam { name: "disconnect".into(), list: true, wrap_list: true, - fields: Some(transform_equals( - where_params.into_iter().map(|item| item.field()).collect(), - )), + fields: Some(transform_equals(where_params.into_iter().map(|item| item.field()).collect())), ..Default::default() }]), ..Default::default() @@ -6804,10 +6631,7 @@ impl<'a> FileFindMany<'a> { } } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -6820,10 +6644,7 @@ impl<'a> FileFindFirst<'a> { self.query.perform::>().await.unwrap() } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -6874,10 +6695,7 @@ impl<'a> FileFindUnique<'a> { } } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -6898,10 +6716,7 @@ impl<'a> FileUpdateUnique<'a> { self.query.perform::().await.unwrap() } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -6914,10 +6729,7 @@ impl<'a> FileUpdateMany<'a> { self.query.perform::>().await.unwrap() } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -7001,13 +6813,7 @@ impl<'a> FileActions<'a> { }; FileFindMany { query } } - pub fn create_one( - &self, - stem: FileSetStem, - name: FileSetName, - size_in_bytes: FileSetSizeInBytes, - params: Vec, - ) -> FileCreateOne { + pub fn create_one(&self, stem: FileSetStem, name: FileSetName, size_in_bytes: FileSetSizeInBytes, params: Vec) -> FileCreateOne { let mut input_fields = params.into_iter().map(|p| p.field()).collect::>(); input_fields.push(FileSetParam::from(stem).field()); input_fields.push(FileSetParam::from(name).field()); @@ -7062,10 +6868,7 @@ impl TagData { pub fn tag_files(&self) -> Result<&Vec, String> { match self.tag_files.as_ref() { Some(v) => Ok(v), - None => Err( - "attempted to access tag_files but did not fetch it using the .with() syntax" - .to_string(), - ), + None => Err("attempted to access tag_files but did not fetch it using the .with() syntax".to_string()), } } } @@ -7791,9 +7594,7 @@ impl TagSetParam { name: "tag_files".into(), fields: Some(vec![Field { name: "connect".into(), - fields: Some(transform_equals( - where_params.into_iter().map(|item| item.field()).collect(), - )), + fields: Some(transform_equals(where_params.into_iter().map(|item| item.field()).collect())), list: true, wrap_list: true, ..Default::default() @@ -7806,9 +7607,7 @@ impl TagSetParam { name: "disconnect".into(), list: true, wrap_list: true, - fields: Some(transform_equals( - where_params.into_iter().map(|item| item.field()).collect(), - )), + fields: Some(transform_equals(where_params.into_iter().map(|item| item.field()).collect())), ..Default::default() }]), ..Default::default() @@ -7863,10 +7662,7 @@ impl<'a> TagFindMany<'a> { } } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -7879,10 +7675,7 @@ impl<'a> TagFindFirst<'a> { self.query.perform::>().await.unwrap() } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -7933,10 +7726,7 @@ impl<'a> TagFindUnique<'a> { } } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -7957,10 +7747,7 @@ impl<'a> TagUpdateUnique<'a> { self.query.perform::().await.unwrap() } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -7973,10 +7760,7 @@ impl<'a> TagUpdateMany<'a> { self.query.perform::>().await.unwrap() } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -8079,11 +7863,7 @@ impl<'a> TagActions<'a> { } } fn tag_on_file_outputs() -> Vec { - vec![ - Output::new("date_created"), - Output::new("tag_id"), - Output::new("file_id"), - ] + vec![Output::new("date_created"), Output::new("tag_id"), Output::new("file_id")] } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TagOnFileData { @@ -8102,18 +7882,13 @@ impl TagOnFileData { pub fn tag(&self) -> Result<&TagData, String> { match self.tag.as_ref() { Some(v) => Ok(v), - None => Err( - "attempted to access tag but did not fetch it using the .with() syntax".to_string(), - ), + None => Err("attempted to access tag but did not fetch it using the .with() syntax".to_string()), } } pub fn file(&self) -> Result<&FileData, String> { match self.file.as_ref() { Some(v) => Ok(v), - None => Err( - "attempted to access file but did not fetch it using the .with() syntax" - .to_string(), - ), + None => Err("attempted to access file but did not fetch it using the .with() syntax".to_string()), } } } @@ -8584,10 +8359,7 @@ impl<'a> TagOnFileFindMany<'a> { } } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -8600,10 +8372,7 @@ impl<'a> TagOnFileFindFirst<'a> { self.query.perform::>().await.unwrap() } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -8654,10 +8423,7 @@ impl<'a> TagOnFileFindUnique<'a> { } } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -8678,10 +8444,7 @@ impl<'a> TagOnFileUpdateUnique<'a> { self.query.perform::().await.unwrap() } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -8694,10 +8457,7 @@ impl<'a> TagOnFileUpdateMany<'a> { self.query.perform::>().await.unwrap() } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -8781,12 +8541,7 @@ impl<'a> TagOnFileActions<'a> { }; TagOnFileFindMany { query } } - pub fn create_one( - &self, - tag: TagOnFileLinkTag, - file: TagOnFileLinkFile, - params: Vec, - ) -> TagOnFileCreateOne { + pub fn create_one(&self, tag: TagOnFileLinkTag, file: TagOnFileLinkFile, params: Vec) -> TagOnFileCreateOne { let mut input_fields = params.into_iter().map(|p| p.field()).collect::>(); input_fields.push(TagOnFileSetParam::from(tag).field()); input_fields.push(TagOnFileSetParam::from(file).field()); @@ -8846,10 +8601,7 @@ impl JobData { pub fn clients(&self) -> Result<&ClientData, String> { match self.clients.as_ref() { Some(v) => Ok(v), - None => Err( - "attempted to access clients but did not fetch it using the .with() syntax" - .to_string(), - ), + None => Err("attempted to access clients but did not fetch it using the .with() syntax".to_string()), } } } @@ -9789,10 +9541,7 @@ impl<'a> JobFindMany<'a> { } } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -9805,10 +9554,7 @@ impl<'a> JobFindFirst<'a> { self.query.perform::>().await.unwrap() } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -9859,10 +9605,7 @@ impl<'a> JobFindUnique<'a> { } } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -9883,10 +9626,7 @@ impl<'a> JobUpdateUnique<'a> { self.query.perform::().await.unwrap() } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -9899,10 +9639,7 @@ impl<'a> JobUpdateMany<'a> { self.query.perform::>().await.unwrap() } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -9986,12 +9723,7 @@ impl<'a> JobActions<'a> { }; JobFindMany { query } } - pub fn create_one( - &self, - action: JobSetAction, - clients: JobLinkClients, - params: Vec, - ) -> JobCreateOne { + pub fn create_one(&self, action: JobSetAction, clients: JobLinkClients, params: Vec) -> JobCreateOne { let mut input_fields = params.into_iter().map(|p| p.field()).collect::>(); input_fields.push(JobSetParam::from(action).field()); input_fields.push(JobSetParam::from(clients).field()); @@ -10721,10 +10453,7 @@ impl<'a> SpaceFindMany<'a> { } } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -10737,10 +10466,7 @@ impl<'a> SpaceFindFirst<'a> { self.query.perform::>().await.unwrap() } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -10791,10 +10517,7 @@ impl<'a> SpaceFindUnique<'a> { } } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -10815,10 +10538,7 @@ impl<'a> SpaceUpdateUnique<'a> { self.query.perform::().await.unwrap() } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } @@ -10831,10 +10551,7 @@ impl<'a> SpaceUpdateMany<'a> { self.query.perform::>().await.unwrap() } pub fn with(mut self, fetches: Vec) -> Self { - let outputs = fetches - .into_iter() - .map(|f| f.param.output()) - .collect::>(); + let outputs = fetches.into_iter().map(|f| f.param.output()).collect::>(); self.query.outputs.extend(outputs); self } diff --git a/packages/core/src/state/client.rs b/packages/core/src/state/client.rs index 0632fb424..5f4de1c56 100644 --- a/packages/core/src/state/client.rs +++ b/packages/core/src/state/client.rs @@ -86,11 +86,7 @@ impl ClientState { } pub fn get_current_library(&self) -> LibraryState { - match self - .libraries - .iter() - .find(|lib| lib.library_id == self.current_library_id) - { + match self.libraries.iter().find(|lib| lib.library_id == self.current_library_id) { Some(lib) => lib.clone(), None => LibraryState::default(), } diff --git a/packages/core/src/sys/locations.rs b/packages/core/src/sys/locations.rs index 73d79a46d..32e2f7ddf 100644 --- a/packages/core/src/sys/locations.rs +++ b/packages/core/src/sys/locations.rs @@ -9,9 +9,42 @@ use log::info; use serde::{Deserialize, Serialize}; use std::{fs, io, io::Write}; use thiserror::Error; +use ts_rs::TS; pub use crate::prisma::LocationData; +#[derive(Debug, Clone, Serialize, Deserialize, TS)] +pub struct LocationResource { + pub id: i64, + pub name: Option, + pub path: Option, + pub total_capacity: Option, + pub available_capacity: Option, + pub is_removable: bool, + pub is_ejectable: bool, + pub is_root_filesystem: bool, + pub is_online: bool, + #[ts(type = "string")] + pub date_created: chrono::DateTime, +} + +impl Into for LocationData { + fn into(self) -> LocationResource { + LocationResource { + id: self.id, + name: self.name, + path: self.path, + total_capacity: self.total_capacity, + available_capacity: self.available_capacity, + is_removable: self.is_removable, + is_ejectable: self.is_ejectable, + is_root_filesystem: self.is_root_filesystem, + is_online: self.is_online, + date_created: self.date_created, + } + } +} + #[derive(Serialize, Deserialize, Default)] pub struct DotSpacedrive { pub location_uuid: String, @@ -24,8 +57,7 @@ static DOTFILE_NAME: &str = ".spacedrive"; // - accessible on from the local filesystem // - already exists in the database pub async fn check_location(path: &str) -> Result { - let dotfile: DotSpacedrive = match fs::File::open(format!("{}/{}", path.clone(), DOTFILE_NAME)) - { + let dotfile: DotSpacedrive = match fs::File::open(format!("{}/{}", path.clone(), DOTFILE_NAME)) { Ok(file) => serde_json::from_reader(file).unwrap_or(DotSpacedrive::default()), Err(e) => return Err(LocationError::DotfileReadFailure(e)), }; @@ -33,15 +65,13 @@ pub async fn check_location(path: &str) -> Result Ok(dotfile) } -pub async fn get_location(location_id: i64) -> Result { +pub async fn get_location(location_id: i64) -> Result { let db = db::get().await.map_err(|e| LocationError::DBError(e))?; // get location by location_id from db and include location_paths let location = match db .location() - .find_first(vec![ - Location::files().some(vec![File::id().equals(location_id)]) - ]) + .find_first(vec![Location::files().some(vec![File::id().equals(location_id.into())])]) .exec() .await { @@ -51,10 +81,10 @@ pub async fn get_location(location_id: i64) -> Result Result { +pub async fn create_location(path: &str) -> Result { let db = db::get().await.map_err(|e| LocationError::DBError(e))?; let config = client::get(); @@ -64,18 +94,10 @@ pub async fn create_location(path: &str) -> Result Err(e) => return Err(LocationError::FileReadError(e)), } // check if location already exists - let location = match db - .location() - .find_first(vec![Location::path().equals(path.to_string())]) - .exec() - .await - { + let location = match db.location().find_first(vec![Location::path().equals(path.to_string())]).exec().await { Some(location) => location, None => { - info!( - "Location does not exist, creating new location for '{}'", - &path - ); + info!("Location does not exist, creating new location for '{}'", &path); let uuid = uuid::Uuid::new_v4(); // create new location let create_location_params = { @@ -85,9 +107,7 @@ pub async fn create_location(path: &str) -> Result }; info!("Loaded mounted volumes: {:?}", volumes); // find mount with matching path - let volume = volumes - .into_iter() - .find(|mount| path.starts_with(&mount.mount_point)); + let volume = volumes.into_iter().find(|mount| path.starts_with(&mount.mount_point)); let volume_data = match volume { Some(mount) => mount, @@ -106,11 +126,7 @@ pub async fn create_location(path: &str) -> Result ] }; - let location = db - .location() - .create_one(create_location_params) - .exec() - .await; + let location = db.location().create_one(create_location_params).exec().await; info!("Created location: {:?}", location); @@ -139,7 +155,7 @@ pub async fn create_location(path: &str) -> Result } }; - Ok(location) + Ok(location.into()) } #[derive(Error, Debug)] diff --git a/packages/core/src/sys/mod.rs b/packages/core/src/sys/mod.rs index f9a5ad1d7..fe435a1af 100644 --- a/packages/core/src/sys/mod.rs +++ b/packages/core/src/sys/mod.rs @@ -2,6 +2,10 @@ pub mod locations; pub mod volumes; use thiserror::Error; +use crate::CoreError; + +use self::locations::LocationError; + #[derive(Error, Debug)] pub enum SysError { #[error("Location error")] @@ -9,3 +13,9 @@ pub enum SysError { #[error("Error with system volumes")] VolumeError(String), } + +impl From for CoreError { + fn from(e: LocationError) -> Self { + CoreError::SysError(SysError::LocationError(e)) + } +} diff --git a/packages/core/src/sys/volumes.rs b/packages/core/src/sys/volumes.rs index f3765227c..198b33765 100644 --- a/packages/core/src/sys/volumes.rs +++ b/packages/core/src/sys/volumes.rs @@ -39,8 +39,7 @@ pub fn get() -> Result, SysError> { let mut name = disk.name().to_str().unwrap_or("Volume").to_string(); let is_removable = disk.is_removable(); - let file_system = String::from_utf8(disk.file_system().to_vec()) - .unwrap_or_else(|_| "Err".to_string()); + let file_system = String::from_utf8(disk.file_system().to_vec()).unwrap_or_else(|_| "Err".to_string()); let disk_type = match disk.type_() { sysinfo::DiskType::SSD => "SSD".to_string(), @@ -56,15 +55,11 @@ pub fn get() -> Result, SysError> { let mut caption = mount_point.clone(); caption.pop(); let wmic_process = Command::new("cmd") - .args([ - "/C", - &format!("wmic logical disk where Caption='{caption}' get Size"), - ]) + .args(["/C", &format!("wmic logical disk where Caption='{caption}' get Size")]) .output() .expect("failed to execute process"); let wmic_process_output = String::from_utf8(wmic_process.stdout).unwrap(); - let parsed_size = - wmic_process_output.split("\r\r\n").collect::>()[1].to_string(); + let parsed_size = wmic_process_output.split("\r\r\n").collect::>()[1].to_string(); if let Ok(n) = parsed_size.trim().parse::() { total_space = n; diff --git a/packages/core/src/util/time.rs b/packages/core/src/util/time.rs index 3a3712927..fa9551e8e 100644 --- a/packages/core/src/util/time.rs +++ b/packages/core/src/util/time.rs @@ -4,12 +4,12 @@ use std::io; use std::time::{SystemTime, UNIX_EPOCH}; pub fn system_time_to_date_time(system_time: io::Result) -> Result { - // extract system time or resort to current time if failure - let system_time = system_time.unwrap_or(SystemTime::now()); - let std_duration = system_time.duration_since(UNIX_EPOCH)?; - let chrono_duration = chrono::Duration::from_std(std_duration)?; - let unix = NaiveDateTime::from_timestamp(0, 0); - let naive = unix + chrono_duration; - // let date_time: DateTime = Utc.from_local_datetime(&naive).unwrap(); - Ok(naive) + // extract system time or resort to current time if failure + let system_time = system_time.unwrap_or(SystemTime::now()); + let std_duration = system_time.duration_since(UNIX_EPOCH)?; + let chrono_duration = chrono::Duration::from_std(std_duration)?; + let unix = NaiveDateTime::from_timestamp(0, 0); + let naive = unix + chrono_duration; + // let date_time: DateTime = Utc.from_local_datetime(&naive).unwrap(); + Ok(naive) } diff --git a/packages/state/lib/bridge.ts b/packages/state/lib/bridge.ts index f805f6ed9..8d6319a6c 100644 --- a/packages/state/lib/bridge.ts +++ b/packages/state/lib/bridge.ts @@ -1,6 +1,6 @@ -import { ClientQuery, ClientResponse } from '@sd/core'; +import { ClientQuery, CoreResponse } from '@sd/core'; import { EventEmitter } from 'eventemitter3'; -import { useQuery } from 'react-query'; +import { useQuery, UseQueryOptions, UseQueryResult } from 'react-query'; export let transport: BaseTransport | null = null; @@ -8,12 +8,19 @@ export abstract class BaseTransport extends EventEmitter { abstract send(query: ClientQuery): Promise; } -export async function bridge< - K extends ClientQuery['key'], - CQ extends Extract ->(key: K, params?: CQ extends { params: any } ? CQ['params'] : never) { +type KeyType = ClientQuery['key']; +type CQType = Extract; +type CRType = Extract; + +type CQParams = CQ extends { params: any } ? CQ['params'] : never; +type CRData = CR extends { data: any } ? CR['data'] : never; + +export async function bridge, CR extends CRType>( + key: K, + params?: CQParams +): Promise> { const result = (await transport?.send({ key, params } as any)) as any; - console.log(`ClientQueryTransport: [${result?.key}]`, result?.data); + // console.log(`Client Query Transport: [${result?.key}]`, result?.data); return result?.data; } @@ -21,10 +28,10 @@ export function setTransport(_transport: BaseTransport) { transport = _transport; } -export function useBridgeQuery( - key: Parameters[0], - params?: Parameters[1], - options: Parameters[2] = {} +export function useBridgeQuery, CR extends CRType>( + key: K, + params?: CQParams, + options: UseQueryOptions> = {} ) { - return useQuery([key, params], () => bridge(key, params), options); + return useQuery>([key, params], async () => await bridge(key, params), options); }