From b8fecaacc049c57450d00ccce8d5992f35b4a113 Mon Sep 17 00:00:00 2001 From: Chip Senkbeil Date: Tue, 16 May 2023 15:46:24 -0500 Subject: [PATCH] Apply nightly formatting to reorder imports and use module-level import granularity --- distant-core/src/api.rs | 20 +++---- distant-core/src/api/local.rs | 31 +++++------ distant-core/src/api/local/process.rs | 8 ++- distant-core/src/api/local/process/pty.rs | 25 +++++---- distant-core/src/api/local/process/simple.rs | 13 +++-- .../src/api/local/process/simple/tasks.rs | 12 ++--- distant-core/src/api/local/process/wait.rs | 3 +- distant-core/src/api/local/state/process.rs | 15 +++--- .../src/api/local/state/process/instance.rs | 16 +++--- distant-core/src/api/local/state/search.rs | 39 +++++++------- distant-core/src/api/local/state/watcher.rs | 26 +++++---- .../src/api/local/state/watcher/path.rs | 13 +++-- distant-core/src/api/reply.rs | 9 +++- distant-core/src/client.rs | 4 +- distant-core/src/client/ext.rs | 28 +++++----- distant-core/src/client/lsp.rs | 40 +++++++------- distant-core/src/client/lsp/msg.rs | 17 +++--- distant-core/src/client/process.rs | 53 ++++++++----------- distant-core/src/client/searcher.rs | 34 ++++++------ distant-core/src/client/watcher.rs | 35 ++++++------ distant-core/src/credentials.rs | 18 +++++-- distant-core/src/data.rs | 4 +- distant-core/src/data/capabilities.rs | 16 +++--- distant-core/src/data/change.rs | 20 +++---- distant-core/src/data/cmd.rs | 3 +- distant-core/src/data/error.rs | 3 +- distant-core/src/data/filesystem.rs | 4 +- distant-core/src/data/metadata.rs | 12 ++--- distant-core/src/data/pty.rs | 5 +- distant-core/src/data/search.rs | 12 +++-- distant-core/src/data/system.rs | 4 +- distant-core/src/serde_str.rs | 11 ++-- .../tests/stress/distant/large_file.rs | 3 +- distant-core/tests/stress/distant/watch.rs | 6 ++- distant-core/tests/stress/fixtures.rs | 5 +- distant-net/src/client.rs | 29 +++++----- distant-net/src/client/builder.rs | 9 ++-- distant-net/src/client/builder/tcp.rs | 8 +-- distant-net/src/client/builder/unix.rs | 7 ++- distant-net/src/client/builder/windows.rs | 8 +-- distant-net/src/client/channel.rs | 22 +++++--- distant-net/src/client/channel/mailbox.rs | 19 +++---- distant-net/src/client/config.rs | 3 +- distant-net/src/client/reconnect.rs | 6 ++- distant-net/src/client/shutdown.rs | 3 +- .../common/authentication/authenticator.rs | 14 +++-- .../src/common/authentication/handler.rs | 8 +-- .../common/authentication/handler/methods.rs | 6 ++- .../authentication/handler/methods/prompt.rs | 8 +-- .../handler/methods/static_key.rs | 11 ++-- .../src/common/authentication/keychain.rs | 4 +- .../src/common/authentication/methods.rs | 13 +++-- .../src/common/authentication/methods/none.rs | 6 ++- .../authentication/methods/static_key.rs | 15 +++--- distant-net/src/common/authentication/msg.rs | 3 +- distant-net/src/common/connection.rs | 22 ++++---- distant-net/src/common/destination.rs | 10 +++- distant-net/src/common/destination/host.rs | 16 +++--- distant-net/src/common/destination/parser.rs | 3 +- distant-net/src/common/listener.rs | 3 +- distant-net/src/common/listener/mapped.rs | 6 ++- distant-net/src/common/listener/mpsc.rs | 6 ++- distant-net/src/common/listener/oneshot.rs | 9 ++-- distant-net/src/common/listener/tcp.rs | 18 ++++--- distant-net/src/common/listener/unix.rs | 22 ++++---- distant-net/src/common/listener/windows.rs | 18 ++++--- distant-net/src/common/map.rs | 20 +++---- distant-net/src/common/packet/request.rs | 13 +++-- distant-net/src/common/packet/response.rs | 13 +++-- distant-net/src/common/port.rs | 15 +++--- distant-net/src/common/transport.rs | 10 ++-- distant-net/src/common/transport/framed.rs | 19 ++++--- .../src/common/transport/framed/backup.rs | 3 +- .../src/common/transport/framed/codec.rs | 6 ++- .../common/transport/framed/codec/chain.rs | 6 ++- .../transport/framed/codec/compression.rs | 25 ++++----- .../transport/framed/codec/encryption.rs | 18 ++++--- .../transport/framed/codec/encryption/key.rs | 10 ++-- .../common/transport/framed/codec/plain.rs | 3 +- .../transport/framed/codec/predicate.rs | 7 ++- .../src/common/transport/framed/exchange.rs | 10 ++-- .../common/transport/framed/exchange/pkb.rs | 4 +- .../common/transport/framed/exchange/salt.rs | 14 ++--- .../src/common/transport/framed/frame.rs | 6 ++- distant-net/src/common/transport/inmemory.rs | 19 ++++--- distant-net/src/common/transport/tcp.rs | 17 ++++-- distant-net/src/common/transport/test.rs | 6 ++- distant-net/src/common/transport/unix.rs | 25 +++++---- distant-net/src/common/transport/windows.rs | 21 ++++---- .../src/common/transport/windows/pipe.rs | 5 +- distant-net/src/common/utils.rs | 21 +++++--- distant-net/src/lib.rs | 4 +- distant-net/src/manager/client.rs | 24 ++++----- distant-net/src/manager/client/channel.rs | 19 ++++--- distant-net/src/manager/data/capabilities.rs | 16 +++--- distant-net/src/manager/data/info.rs | 3 +- distant-net/src/manager/data/list.rs | 10 ++-- distant-net/src/manager/data/request.rs | 8 +-- distant-net/src/manager/data/response.rs | 8 +-- distant-net/src/manager/server.rs | 26 +++++---- .../src/manager/server/authentication.rs | 15 +++--- distant-net/src/manager/server/config.rs | 3 +- distant-net/src/manager/server/connection.rs | 18 ++++--- distant-net/src/manager/server/handler.rs | 13 +++-- distant-net/src/server.rs | 28 ++++++---- distant-net/src/server/builder.rs | 2 - distant-net/src/server/builder/tcp.rs | 24 ++++++--- distant-net/src/server/builder/unix.rs | 23 +++++--- distant-net/src/server/builder/windows.rs | 24 +++++---- distant-net/src/server/config.rs | 5 +- distant-net/src/server/connection.rs | 49 +++++++++-------- distant-net/src/server/context.rs | 3 +- distant-net/src/server/ref.rs | 16 +++--- distant-net/src/server/ref/tcp.rs | 3 +- distant-net/src/server/ref/unix.rs | 3 +- distant-net/src/server/ref/windows.rs | 3 +- distant-net/src/server/reply.rs | 9 +++- distant-net/src/server/shutdown_timer.rs | 8 +-- distant-net/src/server/state.rs | 5 +- distant-net/tests/manager_tests.rs | 5 +- distant-net/tests/typed_tests.rs | 2 +- distant-net/tests/untyped_tests.rs | 2 +- distant-ssh2/src/api.rs | 32 +++++------ distant-ssh2/src/lib.rs | 31 +++++------ distant-ssh2/src/process.rs | 20 ++++--- distant-ssh2/src/utils.rs | 12 ++--- distant-ssh2/tests/ssh2/client.rs | 17 +++--- distant-ssh2/tests/ssh2/launched.rs | 16 +++--- distant-ssh2/tests/ssh2/ssh.rs | 3 +- distant-ssh2/tests/sshd/mod.rs | 34 ++++++------ distant-ssh2/tests/utils/mod.rs | 3 +- rustfmt.toml | 10 ++-- src/cli.rs | 8 ++- src/cli/commands/client.rs | 33 +++++++----- src/cli/commands/client/lsp.rs | 11 ++-- src/cli/commands/client/shell.rs | 24 ++++----- src/cli/commands/common/format.rs | 26 ++++----- src/cli/commands/common/link.rs | 10 ++-- src/cli/commands/common/stdin.rs | 7 ++- src/cli/commands/generate.rs | 8 +-- src/cli/commands/manager.rs | 18 ++++--- src/cli/commands/manager/handlers.rs | 24 ++++----- src/cli/commands/server.rs | 14 +++-- src/cli/common/cache.rs | 10 ++-- src/cli/common/cache/id.rs | 11 ++-- src/cli/common/client.rs | 10 ++-- src/cli/common/manager.rs | 7 ++- src/cli/common/msg.rs | 12 ++--- src/cli/common/spawner.rs | 15 +++--- src/constants.rs | 3 +- src/lib.rs | 3 +- src/options.rs | 19 ++++--- src/options/common/address.rs | 10 ++-- src/options/common/cmd.rs | 3 +- src/options/common/logging.rs | 3 +- src/options/common/network.rs | 3 +- src/options/common/search.rs | 5 +- src/options/common/value.rs | 5 +- src/options/config.rs | 16 +++--- src/options/config/client.rs | 3 +- src/options/config/client/launch.rs | 3 +- src/options/config/generate.rs | 3 +- src/options/config/manager.rs | 3 +- src/options/config/server.rs | 3 +- src/options/config/server/listen.rs | 6 ++- src/win_service.rs | 28 +++++----- tests/cli/api/capabilities.rs | 3 +- tests/cli/api/copy.rs | 3 +- tests/cli/api/dir_create.rs | 3 +- tests/cli/api/dir_read.rs | 6 ++- tests/cli/api/exists.rs | 3 +- tests/cli/api/file_append.rs | 3 +- tests/cli/api/file_append_text.rs | 3 +- tests/cli/api/file_read.rs | 3 +- tests/cli/api/file_read_text.rs | 3 +- tests/cli/api/file_write.rs | 3 +- tests/cli/api/file_write_text.rs | 3 +- tests/cli/api/metadata.rs | 3 +- tests/cli/api/proc_spawn.rs | 4 +- tests/cli/api/remove.rs | 3 +- tests/cli/api/rename.rs | 3 +- tests/cli/api/search.rs | 3 +- tests/cli/api/system_info.rs | 6 ++- tests/cli/api/watch.rs | 6 ++- tests/cli/client/capabilities.rs | 3 +- tests/cli/client/fs_copy.rs | 3 +- tests/cli/client/fs_exists.rs | 3 +- tests/cli/client/fs_make_dir.rs | 3 +- tests/cli/client/fs_metadata.rs | 4 +- tests/cli/client/fs_read_directory.rs | 7 ++- tests/cli/client/fs_read_file.rs | 3 +- tests/cli/client/fs_remove.rs | 3 +- tests/cli/client/fs_rename.rs | 3 +- tests/cli/client/fs_search.rs | 3 +- tests/cli/client/fs_watch.rs | 8 ++- tests/cli/client/fs_write.rs | 3 +- tests/cli/client/spawn.rs | 5 +- tests/cli/client/system_info.rs | 6 ++- tests/cli/fixtures.rs | 18 +++---- tests/cli/fixtures/api.rs | 11 ++-- tests/cli/manager/capabilities.rs | 3 +- tests/cli/utils/reader.rs | 11 ++-- 202 files changed, 1306 insertions(+), 1002 deletions(-) diff --git a/distant-core/src/api.rs b/distant-core/src/api.rs index 9f9e1c8..ced8018 100644 --- a/distant-core/src/api.rs +++ b/distant-core/src/api.rs @@ -1,15 +1,17 @@ -use crate::{ - data::{ - Capabilities, ChangeKind, DirEntry, Environment, Error, Metadata, ProcessId, PtySize, - SearchId, SearchQuery, SystemInfo, - }, - DistantMsg, DistantRequestData, DistantResponseData, -}; +use std::io; +use std::path::PathBuf; +use std::sync::Arc; + use async_trait::async_trait; use distant_net::common::ConnectionId; use distant_net::server::{ConnectionCtx, Reply, ServerCtx, ServerHandler}; use log::*; -use std::{io, path::PathBuf, sync::Arc}; + +use crate::data::{ + Capabilities, ChangeKind, DirEntry, Environment, Error, Metadata, ProcessId, PtySize, SearchId, + SearchQuery, SystemInfo, +}; +use crate::{DistantMsg, DistantRequestData, DistantResponseData}; mod local; pub use local::LocalDistantApi; @@ -420,9 +422,9 @@ where T: DistantApi + Send + Sync, D: Send + Sync, { + type LocalData = D; type Request = DistantMsg; type Response = DistantMsg; - type LocalData = D; /// Overridden to leverage [`DistantApi`] implementation of `on_accept` async fn on_accept(&self, ctx: ConnectionCtx<'_, Self::LocalData>) -> io::Result<()> { diff --git a/distant-core/src/api/local.rs b/distant-core/src/api/local.rs index 1cc8fce..bc6d4cc 100644 --- a/distant-core/src/api/local.rs +++ b/distant-core/src/api/local.rs @@ -1,19 +1,17 @@ -use crate::{ - data::{ - Capabilities, ChangeKind, ChangeKindSet, DirEntry, Environment, FileType, Metadata, - ProcessId, PtySize, SearchId, SearchQuery, SystemInfo, - }, - DistantApi, DistantCtx, -}; +use std::io; +use std::path::{Path, PathBuf}; + use async_trait::async_trait; use log::*; -use std::{ - io, - path::{Path, PathBuf}, -}; use tokio::io::AsyncWriteExt; use walkdir::WalkDir; +use crate::data::{ + Capabilities, ChangeKind, ChangeKindSet, DirEntry, Environment, FileType, Metadata, ProcessId, + PtySize, SearchId, SearchQuery, SystemInfo, +}; +use crate::{DistantApi, DistantCtx}; + mod process; mod state; @@ -493,17 +491,20 @@ impl DistantApi for LocalDistantApi { #[cfg(test)] mod tests { - use super::*; - use crate::api::ConnectionCtx; - use crate::data::DistantResponseData; + use std::sync::Arc; + use std::time::Duration; + use assert_fs::prelude::*; use distant_net::server::Reply; use once_cell::sync::Lazy; use predicates::prelude::*; - use std::{sync::Arc, time::Duration}; use test_log::test; use tokio::sync::mpsc; + use super::*; + use crate::api::ConnectionCtx; + use crate::data::DistantResponseData; + static TEMP_SCRIPT_DIR: Lazy = Lazy::new(|| assert_fs::TempDir::new().unwrap()); static SCRIPT_RUNNER: Lazy = Lazy::new(|| String::from("bash")); diff --git a/distant-core/src/api/local/process.rs b/distant-core/src/api/local/process.rs index 562b6d4..c0d7826 100644 --- a/distant-core/src/api/local/process.rs +++ b/distant-core/src/api/local/process.rs @@ -1,6 +1,10 @@ +use std::future::Future; +use std::pin::Pin; + +use tokio::io; +use tokio::sync::mpsc; + use crate::data::{ProcessId, PtySize}; -use std::{future::Future, pin::Pin}; -use tokio::{io, sync::mpsc}; mod pty; pub use pty::*; diff --git a/distant-core/src/api/local/process/pty.rs b/distant-core/src/api/local/process/pty.rs index dc08ec5..3b2fb6e 100644 --- a/distant-core/src/api/local/process/pty.rs +++ b/distant-core/src/api/local/process/pty.rs @@ -1,20 +1,19 @@ +use std::ffi::OsStr; +use std::io::{self, Read, Write}; +use std::path::PathBuf; +use std::sync::{Arc, Mutex, Weak}; + +use log::*; +use portable_pty::{CommandBuilder, MasterPty, PtySize as PortablePtySize}; +use tokio::sync::mpsc; +use tokio::task::JoinHandle; + use super::{ wait, ExitStatus, FutureReturn, InputChannel, OutputChannel, Process, ProcessId, ProcessKiller, ProcessPty, PtySize, WaitRx, }; -use crate::{ - constants::{MAX_PIPE_CHUNK_SIZE, READ_PAUSE_DURATION}, - data::Environment, -}; -use log::*; -use portable_pty::{CommandBuilder, MasterPty, PtySize as PortablePtySize}; -use std::{ - ffi::OsStr, - io::{self, Read, Write}, - path::PathBuf, - sync::{Arc, Mutex, Weak}, -}; -use tokio::{sync::mpsc, task::JoinHandle}; +use crate::constants::{MAX_PIPE_CHUNK_SIZE, READ_PAUSE_DURATION}; +use crate::data::Environment; /// Represents a process that is associated with a pty pub struct PtyProcess { diff --git a/distant-core/src/api/local/process/simple.rs b/distant-core/src/api/local/process/simple.rs index a997647..3fa14b2 100644 --- a/distant-core/src/api/local/process/simple.rs +++ b/distant-core/src/api/local/process/simple.rs @@ -1,11 +1,18 @@ +use std::ffi::OsStr; +use std::path::PathBuf; +use std::process::Stdio; + +use log::*; +use tokio::io; +use tokio::process::Command; +use tokio::sync::mpsc; +use tokio::task::JoinHandle; + use super::{ wait, ExitStatus, FutureReturn, InputChannel, NoProcessPty, OutputChannel, Process, ProcessId, ProcessKiller, WaitRx, }; use crate::data::Environment; -use log::*; -use std::{ffi::OsStr, path::PathBuf, process::Stdio}; -use tokio::{io, process::Command, sync::mpsc, task::JoinHandle}; mod tasks; diff --git a/distant-core/src/api/local/process/simple/tasks.rs b/distant-core/src/api/local/process/simple/tasks.rs index 6aa06ad..eed0997 100644 --- a/distant-core/src/api/local/process/simple/tasks.rs +++ b/distant-core/src/api/local/process/simple/tasks.rs @@ -1,10 +1,10 @@ -use crate::constants::{MAX_PIPE_CHUNK_SIZE, READ_PAUSE_DURATION}; use std::io; -use tokio::{ - io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}, - sync::mpsc, - task::JoinHandle, -}; + +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; +use tokio::sync::mpsc; +use tokio::task::JoinHandle; + +use crate::constants::{MAX_PIPE_CHUNK_SIZE, READ_PAUSE_DURATION}; pub fn spawn_read_task( reader: R, diff --git a/distant-core/src/api/local/process/wait.rs b/distant-core/src/api/local/process/wait.rs index 8a77668..cd3b570 100644 --- a/distant-core/src/api/local/process/wait.rs +++ b/distant-core/src/api/local/process/wait.rs @@ -1,4 +1,5 @@ -use tokio::{io, sync::mpsc}; +use tokio::io; +use tokio::sync::mpsc; /// Exit status of a remote process #[derive(Copy, Clone, Debug, PartialEq, Eq)] diff --git a/distant-core/src/api/local/state/process.rs b/distant-core/src/api/local/state/process.rs index 65efabc..0bcc120 100644 --- a/distant-core/src/api/local/state/process.rs +++ b/distant-core/src/api/local/state/process.rs @@ -1,10 +1,13 @@ -use crate::data::{DistantResponseData, Environment, ProcessId, PtySize}; +use std::collections::HashMap; +use std::io; +use std::ops::Deref; +use std::path::PathBuf; + use distant_net::server::Reply; -use std::{collections::HashMap, io, ops::Deref, path::PathBuf}; -use tokio::{ - sync::{mpsc, oneshot}, - task::JoinHandle, -}; +use tokio::sync::{mpsc, oneshot}; +use tokio::task::JoinHandle; + +use crate::data::{DistantResponseData, Environment, ProcessId, PtySize}; mod instance; pub use instance::*; diff --git a/distant-core/src/api/local/state/process/instance.rs b/distant-core/src/api/local/state/process/instance.rs index c78d4d3..011dbd1 100644 --- a/distant-core/src/api/local/state/process/instance.rs +++ b/distant-core/src/api/local/state/process/instance.rs @@ -1,14 +1,16 @@ -use crate::{ - api::local::process::{ - InputChannel, OutputChannel, Process, ProcessKiller, ProcessPty, PtyProcess, SimpleProcess, - }, - data::{DistantResponseData, Environment, ProcessId, PtySize}, -}; +use std::future::Future; +use std::io; +use std::path::PathBuf; + use distant_net::server::Reply; use log::*; -use std::{future::Future, io, path::PathBuf}; use tokio::task::JoinHandle; +use crate::api::local::process::{ + InputChannel, OutputChannel, Process, ProcessKiller, ProcessPty, PtyProcess, SimpleProcess, +}; +use crate::data::{DistantResponseData, Environment, ProcessId, PtySize}; + /// Holds information related to a spawned process on the server pub struct ProcessInstance { pub cmd: String, diff --git a/distant-core/src/api/local/state/search.rs b/distant-core/src/api/local/state/search.rs index 668ed14..432068b 100644 --- a/distant-core/src/api/local/state/search.rs +++ b/distant-core/src/api/local/state/search.rs @@ -1,24 +1,23 @@ +use std::collections::HashMap; +use std::ops::Deref; +use std::path::Path; +use std::{cmp, io}; + +use distant_net::server::Reply; +use grep::matcher::Matcher; +use grep::regex::{RegexMatcher, RegexMatcherBuilder}; +use grep::searcher::{BinaryDetection, Searcher, SearcherBuilder, Sink, SinkMatch}; +use ignore::types::TypesBuilder; +use ignore::{DirEntry, ParallelVisitor, ParallelVisitorBuilder, WalkBuilder, WalkParallel}; +use log::*; +use tokio::sync::{broadcast, mpsc, oneshot}; +use tokio::task::JoinHandle; + use crate::data::{ DistantResponseData, SearchId, SearchQuery, SearchQueryContentsMatch, SearchQueryMatch, SearchQueryMatchData, SearchQueryOptions, SearchQueryPathMatch, SearchQuerySubmatch, SearchQueryTarget, }; -use distant_net::server::Reply; -use grep::{ - matcher::Matcher, - regex::{RegexMatcher, RegexMatcherBuilder}, - searcher::{BinaryDetection, Searcher, SearcherBuilder, Sink, SinkMatch}, -}; -use ignore::{ - types::TypesBuilder, DirEntry, ParallelVisitor, ParallelVisitorBuilder, WalkBuilder, - WalkParallel, -}; -use log::*; -use std::{cmp, collections::HashMap, io, ops::Deref, path::Path}; -use tokio::{ - sync::{broadcast, mpsc, oneshot}, - task::JoinHandle, -}; const MAXIMUM_SEARCH_THREADS: usize = 12; @@ -808,12 +807,14 @@ where #[cfg(test)] mod tests { - use super::*; - use crate::data::{FileType, SearchQueryCondition, SearchQueryMatchData}; - use assert_fs::prelude::*; use std::path::PathBuf; + + use assert_fs::prelude::*; use test_log::test; + use super::*; + use crate::data::{FileType, SearchQueryCondition, SearchQueryMatchData}; + fn make_path(path: &str) -> PathBuf { use std::path::MAIN_SEPARATOR; diff --git a/distant-core/src/api/local/state/watcher.rs b/distant-core/src/api/local/state/watcher.rs index b50aabe..7b45fbe 100644 --- a/distant-core/src/api/local/state/watcher.rs +++ b/distant-core/src/api/local/state/watcher.rs @@ -1,23 +1,21 @@ -use crate::{constants::SERVER_WATCHER_CAPACITY, data::ChangeKind}; +use std::collections::HashMap; +use std::io; +use std::ops::Deref; +use std::path::{Path, PathBuf}; + use distant_net::common::ConnectionId; use log::*; use notify::{ Config as WatcherConfig, Error as WatcherError, ErrorKind as WatcherErrorKind, Event as WatcherEvent, PollWatcher, RecursiveMode, Watcher, }; -use std::{ - collections::HashMap, - io, - ops::Deref, - path::{Path, PathBuf}, -}; -use tokio::{ - sync::{ - mpsc::{self, error::TrySendError}, - oneshot, - }, - task::JoinHandle, -}; +use tokio::sync::mpsc::error::TrySendError; +use tokio::sync::mpsc::{self}; +use tokio::sync::oneshot; +use tokio::task::JoinHandle; + +use crate::constants::SERVER_WATCHER_CAPACITY; +use crate::data::ChangeKind; mod path; pub use path::*; diff --git a/distant-core/src/api/local/state/watcher/path.rs b/distant-core/src/api/local/state/watcher/path.rs index aea9d7e..ddfc394 100644 --- a/distant-core/src/api/local/state/watcher/path.rs +++ b/distant-core/src/api/local/state/watcher/path.rs @@ -1,12 +1,11 @@ -use crate::data::{Change, ChangeKind, ChangeKindSet, DistantResponseData, Error}; +use std::hash::{Hash, Hasher}; +use std::path::{Path, PathBuf}; +use std::{fmt, io}; + use distant_net::common::ConnectionId; use distant_net::server::Reply; -use std::{ - fmt, - hash::{Hash, Hasher}, - io, - path::{Path, PathBuf}, -}; + +use crate::data::{Change, ChangeKind, ChangeKindSet, DistantResponseData, Error}; /// Represents a path registered with a watcher that includes relevant state including /// the ability to reply with diff --git a/distant-core/src/api/reply.rs b/distant-core/src/api/reply.rs index 0dd9349..843c445 100644 --- a/distant-core/src/api/reply.rs +++ b/distant-core/src/api/reply.rs @@ -1,6 +1,11 @@ -use crate::{api::DistantMsg, data::DistantResponseData}; +use std::future::Future; +use std::io; +use std::pin::Pin; + use distant_net::server::Reply; -use std::{future::Future, io, pin::Pin}; + +use crate::api::DistantMsg; +use crate::data::DistantResponseData; /// Wrapper around a reply that can be batch or single, converting /// a single data into the wrapped type diff --git a/distant-core/src/client.rs b/distant-core/src/client.rs index 3354c1b..9d2e48f 100644 --- a/distant-core/src/client.rs +++ b/distant-core/src/client.rs @@ -1,5 +1,7 @@ +use distant_net::client::Channel; +use distant_net::Client; + use crate::{DistantMsg, DistantRequestData, DistantResponseData}; -use distant_net::{client::Channel, Client}; mod ext; mod lsp; diff --git a/distant-core/src/client/ext.rs b/distant-core/src/client/ext.rs index 9532ca0..d49ae1c 100644 --- a/distant-core/src/client/ext.rs +++ b/distant-core/src/client/ext.rs @@ -1,16 +1,20 @@ -use crate::{ - client::{ - RemoteCommand, RemoteLspCommand, RemoteLspProcess, RemoteOutput, RemoteProcess, Searcher, - Watcher, - }, - data::{ - Capabilities, ChangeKindSet, DirEntry, DistantRequestData, DistantResponseData, - Environment, Error as Failure, Metadata, PtySize, SearchId, SearchQuery, SystemInfo, - }, - DistantMsg, +use std::future::Future; +use std::io; +use std::path::PathBuf; +use std::pin::Pin; + +use distant_net::client::Channel; +use distant_net::common::Request; + +use crate::client::{ + RemoteCommand, RemoteLspCommand, RemoteLspProcess, RemoteOutput, RemoteProcess, Searcher, + Watcher, +}; +use crate::data::{ + Capabilities, ChangeKindSet, DirEntry, DistantRequestData, DistantResponseData, Environment, + Error as Failure, Metadata, PtySize, SearchId, SearchQuery, SystemInfo, }; -use distant_net::{client::Channel, common::Request}; -use std::{future::Future, io, path::PathBuf, pin::Pin}; +use crate::DistantMsg; pub type AsyncReturn<'a, T, E = io::Error> = Pin> + Send + 'a>>; diff --git a/distant-core/src/client/lsp.rs b/distant-core/src/client/lsp.rs index 09bf85d..873704f 100644 --- a/distant-core/src/client/lsp.rs +++ b/distant-core/src/client/lsp.rs @@ -1,20 +1,17 @@ -use crate::{ - client::{ - DistantChannel, RemoteCommand, RemoteProcess, RemoteStatus, RemoteStderr, RemoteStdin, - RemoteStdout, - }, - data::{Environment, PtySize}, -}; +use std::io::{self, Cursor, Read}; +use std::ops::{Deref, DerefMut}; +use std::path::PathBuf; + use futures::stream::{Stream, StreamExt}; -use std::{ - io::{self, Cursor, Read}, - ops::{Deref, DerefMut}, - path::PathBuf, -}; -use tokio::{ - sync::mpsc::{self, error::TryRecvError}, - task::JoinHandle, +use tokio::sync::mpsc::error::TryRecvError; +use tokio::sync::mpsc::{self}; +use tokio::task::JoinHandle; + +use crate::client::{ + DistantChannel, RemoteCommand, RemoteProcess, RemoteStatus, RemoteStderr, RemoteStdin, + RemoteStdout, }; +use crate::data::{Environment, PtySize}; mod msg; pub use msg::*; @@ -397,14 +394,15 @@ fn read_lsp_messages(input: &[u8]) -> io::Result<(Option>, Vec)> #[cfg(test)] mod tests { + use std::future::Future; + use std::time::Duration; + + use distant_net::common::{FramedTransport, InmemoryTransport, Request, Response}; + use distant_net::Client; + use test_log::test; + use super::*; use crate::data::{DistantRequestData, DistantResponseData}; - use distant_net::{ - common::{FramedTransport, InmemoryTransport, Request, Response}, - Client, - }; - use std::{future::Future, time::Duration}; - use test_log::test; /// Timeout used with timeout function const TIMEOUT: Duration = Duration::from_millis(50); diff --git a/distant-core/src/client/lsp/msg.rs b/distant-core/src/client/lsp/msg.rs index 86e27f5..5996df4 100644 --- a/distant-core/src/client/lsp/msg.rs +++ b/distant-core/src/client/lsp/msg.rs @@ -1,13 +1,12 @@ +use std::fmt; +use std::io::{self, BufRead}; +use std::ops::{Deref, DerefMut}; +use std::str::FromStr; +use std::string::FromUtf8Error; + use derive_more::{Display, Error, From}; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; -use std::{ - fmt, - io::{self, BufRead}, - ops::{Deref, DerefMut}, - str::FromStr, - string::FromUtf8Error, -}; /// Represents some data being communicated to/from an LSP consisting of a header and content part #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -61,6 +60,7 @@ impl LspMsg { pub fn header(&self) -> &LspHeader { &self.header } + /// Returns a mutable reference to the header part pub fn mut_header(&mut self) -> &mut LspHeader { &mut self.header @@ -395,9 +395,10 @@ impl FromStr for LspContent { #[cfg(test)] mod tests { - use super::*; use test_log::test; + use super::*; + macro_rules! make_obj { ($($tail:tt)*) => { match serde_json::json!($($tail)*) { diff --git a/distant-core/src/client/process.rs b/distant-core/src/client/process.rs index 6defd7d..827364c 100644 --- a/distant-core/src/client/process.rs +++ b/distant-core/src/client/process.rs @@ -1,26 +1,19 @@ -use crate::{ - client::DistantChannel, - constants::CLIENT_PIPE_CAPACITY, - data::{Cmd, DistantRequestData, DistantResponseData, Environment, ProcessId, PtySize}, - DistantMsg, -}; -use distant_net::{ - client::Mailbox, - common::{Request, Response}, -}; +use std::path::PathBuf; +use std::sync::Arc; + +use distant_net::client::Mailbox; +use distant_net::common::{Request, Response}; use log::*; -use std::{path::PathBuf, sync::Arc}; -use tokio::{ - io, - sync::{ - mpsc::{ - self, - error::{TryRecvError, TrySendError}, - }, - RwLock, - }, - task::JoinHandle, -}; +use tokio::io; +use tokio::sync::mpsc::error::{TryRecvError, TrySendError}; +use tokio::sync::mpsc::{self}; +use tokio::sync::RwLock; +use tokio::task::JoinHandle; + +use crate::client::DistantChannel; +use crate::constants::CLIENT_PIPE_CAPACITY; +use crate::data::{Cmd, DistantRequestData, DistantResponseData, Environment, ProcessId, PtySize}; +use crate::DistantMsg; #[derive(Clone, Debug, PartialEq, Eq)] pub struct RemoteOutput { @@ -595,18 +588,16 @@ mod errors { #[cfg(test)] mod tests { - use super::*; - use crate::{ - client::DistantClient, - data::{Error, ErrorKind}, - }; - use distant_net::{ - common::{FramedTransport, InmemoryTransport, Response}, - Client, - }; use std::time::Duration; + + use distant_net::common::{FramedTransport, InmemoryTransport, Response}; + use distant_net::Client; use test_log::test; + use super::*; + use crate::client::DistantClient; + use crate::data::{Error, ErrorKind}; + fn make_session() -> (FramedTransport, DistantClient) { let (t1, t2) = FramedTransport::pair(100); (t1, Client::spawn_inmemory(t2, Default::default())) diff --git a/distant-core/src/client/searcher.rs b/distant-core/src/client/searcher.rs index 3a831f7..d961a93 100644 --- a/distant-core/src/client/searcher.rs +++ b/distant-core/src/client/searcher.rs @@ -1,13 +1,16 @@ -use crate::{ - client::{DistantChannel, DistantChannelExt}, - constants::CLIENT_SEARCHER_CAPACITY, - data::{DistantRequestData, DistantResponseData, SearchId, SearchQuery, SearchQueryMatch}, - DistantMsg, -}; +use std::{fmt, io}; + use distant_net::common::Request; use log::*; -use std::{fmt, io}; -use tokio::{sync::mpsc, task::JoinHandle}; +use tokio::sync::mpsc; +use tokio::task::JoinHandle; + +use crate::client::{DistantChannel, DistantChannelExt}; +use crate::constants::CLIENT_SEARCHER_CAPACITY; +use crate::data::{ + DistantRequestData, DistantResponseData, SearchId, SearchQuery, SearchQueryMatch, +}; +use crate::DistantMsg; /// Represents a searcher for files, directories, and symlinks on the filesystem pub struct Searcher { @@ -190,19 +193,20 @@ impl Searcher { #[cfg(test)] mod tests { + use std::path::PathBuf; + use std::sync::Arc; + + use distant_net::common::{FramedTransport, InmemoryTransport, Response}; + use distant_net::Client; + use test_log::test; + use tokio::sync::Mutex; + use super::*; use crate::data::{ SearchQueryCondition, SearchQueryMatchData, SearchQueryOptions, SearchQueryPathMatch, SearchQuerySubmatch, SearchQueryTarget, }; use crate::DistantClient; - use distant_net::{ - common::{FramedTransport, InmemoryTransport, Response}, - Client, - }; - use std::{path::PathBuf, sync::Arc}; - use test_log::test; - use tokio::sync::Mutex; fn make_session() -> (FramedTransport, DistantClient) { let (t1, t2) = FramedTransport::pair(100); diff --git a/distant-core/src/client/watcher.rs b/distant-core/src/client/watcher.rs index 5c603cc..f0c2d4f 100644 --- a/distant-core/src/client/watcher.rs +++ b/distant-core/src/client/watcher.rs @@ -1,16 +1,15 @@ -use crate::{ - client::{DistantChannel, DistantChannelExt}, - constants::CLIENT_WATCHER_CAPACITY, - data::{Change, ChangeKindSet, DistantRequestData, DistantResponseData}, - DistantMsg, -}; +use std::path::{Path, PathBuf}; +use std::{fmt, io}; + use distant_net::common::Request; use log::*; -use std::{ - fmt, io, - path::{Path, PathBuf}, -}; -use tokio::{sync::mpsc, task::JoinHandle}; +use tokio::sync::mpsc; +use tokio::task::JoinHandle; + +use crate::client::{DistantChannel, DistantChannelExt}; +use crate::constants::CLIENT_WATCHER_CAPACITY; +use crate::data::{Change, ChangeKindSet, DistantRequestData, DistantResponseData}; +use crate::DistantMsg; /// Represents a watcher of some path on a remote machine pub struct Watcher { @@ -181,17 +180,17 @@ impl Watcher { #[cfg(test)] mod tests { - use super::*; - use crate::data::ChangeKind; - use crate::DistantClient; - use distant_net::{ - common::{FramedTransport, InmemoryTransport, Response}, - Client, - }; use std::sync::Arc; + + use distant_net::common::{FramedTransport, InmemoryTransport, Response}; + use distant_net::Client; use test_log::test; use tokio::sync::Mutex; + use super::*; + use crate::data::ChangeKind; + use crate::DistantClient; + fn make_session() -> (FramedTransport, DistantClient) { let (t1, t2) = FramedTransport::pair(100); (t1, Client::spawn_inmemory(t2, Default::default())) diff --git a/distant-core/src/credentials.rs b/distant-core/src/credentials.rs index 0fd4455..272afcc 100644 --- a/distant-core/src/credentials.rs +++ b/distant-core/src/credentials.rs @@ -1,7 +1,13 @@ -use crate::serde_str::{deserialize_from_str, serialize_to_str}; +use std::convert::TryFrom; +use std::str::FromStr; +use std::{fmt, io}; + use distant_net::common::{Destination, Host, SecretKey32}; -use serde::{de::Deserializer, ser::Serializer, Deserialize, Serialize}; -use std::{convert::TryFrom, fmt, io, str::FromStr}; +use serde::de::Deserializer; +use serde::ser::Serializer; +use serde::{Deserialize, Serialize}; + +use crate::serde_str::{deserialize_from_str, serialize_to_str}; const SCHEME: &str = "distant"; const SCHEME_WITH_SEP: &str = "distant://"; @@ -167,11 +173,13 @@ impl TryFrom for Destination { #[cfg(test)] mod tests { - use super::*; - use once_cell::sync::Lazy; use std::net::{Ipv4Addr, Ipv6Addr}; + + use once_cell::sync::Lazy; use test_log::test; + use super::*; + const HOST: &str = "testhost"; const PORT: u16 = 12345; diff --git a/distant-core/src/data.rs b/distant-core/src/data.rs index dcc6c7a..a4b431f 100644 --- a/distant-core/src/data.rs +++ b/distant-core/src/data.rs @@ -1,6 +1,8 @@ +use std::io; +use std::path::PathBuf; + use derive_more::{From, IsVariant}; use serde::{Deserialize, Serialize}; -use std::{io, path::PathBuf}; use strum::{AsRefStr, EnumDiscriminants, EnumIter, EnumMessage, EnumString}; mod capabilities; diff --git a/distant-core/src/data/capabilities.rs b/distant-core/src/data/capabilities.rs index bebd416..45e9b8f 100644 --- a/distant-core/src/data/capabilities.rs +++ b/distant-core/src/data/capabilities.rs @@ -1,15 +1,15 @@ -use super::CapabilityKind; +use std::cmp::Ordering; +use std::collections::HashSet; +use std::hash::{Hash, Hasher}; +use std::ops::{BitAnd, BitOr, BitXor}; +use std::str::FromStr; + use derive_more::{From, Into, IntoIterator}; use serde::{Deserialize, Serialize}; -use std::{ - cmp::Ordering, - collections::HashSet, - hash::{Hash, Hasher}, - ops::{BitAnd, BitOr, BitXor}, - str::FromStr, -}; use strum::{EnumMessage, IntoEnumIterator}; +use super::CapabilityKind; + /// Set of supported capabilities for a server #[derive(Clone, Debug, From, Into, PartialEq, Eq, IntoIterator, Serialize, Deserialize)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] diff --git a/distant-core/src/data/change.rs b/distant-core/src/data/change.rs index b506529..578a337 100644 --- a/distant-core/src/data/change.rs +++ b/distant-core/src/data/change.rs @@ -1,15 +1,15 @@ +use std::collections::HashSet; +use std::fmt; +use std::hash::{Hash, Hasher}; +use std::iter::FromIterator; +use std::ops::{BitOr, Sub}; +use std::path::PathBuf; +use std::str::FromStr; + use derive_more::{Deref, DerefMut, IntoIterator}; -use notify::{event::Event as NotifyEvent, EventKind as NotifyEventKind}; +use notify::event::Event as NotifyEvent; +use notify::EventKind as NotifyEventKind; use serde::{Deserialize, Serialize}; -use std::{ - collections::HashSet, - fmt, - hash::{Hash, Hasher}, - iter::FromIterator, - ops::{BitOr, Sub}, - path::PathBuf, - str::FromStr, -}; use strum::{EnumString, EnumVariantNames, VariantNames}; /// Change to one or more paths on the filesystem diff --git a/distant-core/src/data/cmd.rs b/distant-core/src/data/cmd.rs index 11c7942..74ff005 100644 --- a/distant-core/src/data/cmd.rs +++ b/distant-core/src/data/cmd.rs @@ -1,6 +1,7 @@ +use std::ops::{Deref, DerefMut}; + use derive_more::{Display, From, Into}; use serde::{Deserialize, Serialize}; -use std::ops::{Deref, DerefMut}; /// Represents some command with arguments to execute #[derive(Clone, Debug, Display, From, Into, Hash, PartialEq, Eq, Serialize, Deserialize)] diff --git a/distant-core/src/data/error.rs b/distant-core/src/data/error.rs index 30bbc12..17d6de0 100644 --- a/distant-core/src/data/error.rs +++ b/distant-core/src/data/error.rs @@ -1,7 +1,8 @@ +use std::io; + use derive_more::Display; use notify::ErrorKind as NotifyErrorKind; use serde::{Deserialize, Serialize}; -use std::io; /// General purpose error type that can be sent across the wire #[derive(Clone, Debug, Display, PartialEq, Eq, Serialize, Deserialize)] diff --git a/distant-core/src/data/filesystem.rs b/distant-core/src/data/filesystem.rs index 3cd6d89..b71328d 100644 --- a/distant-core/src/data/filesystem.rs +++ b/distant-core/src/data/filesystem.rs @@ -1,6 +1,8 @@ +use std::fs::FileType as StdFileType; +use std::path::PathBuf; + use derive_more::IsVariant; use serde::{Deserialize, Serialize}; -use std::{fs::FileType as StdFileType, path::PathBuf}; use strum::AsRefStr; /// Represents information about a single entry within a directory diff --git a/distant-core/src/data/metadata.rs b/distant-core/src/data/metadata.rs index 9a42ec2..ad4525e 100644 --- a/distant-core/src/data/metadata.rs +++ b/distant-core/src/data/metadata.rs @@ -1,11 +1,11 @@ -use super::{deserialize_u128_option, serialize_u128_option, FileType}; +use std::io; +use std::path::{Path, PathBuf}; +use std::time::SystemTime; + use bitflags::bitflags; use serde::{Deserialize, Serialize}; -use std::{ - io, - path::{Path, PathBuf}, - time::SystemTime, -}; + +use super::{deserialize_u128_option, serialize_u128_option, FileType}; /// Represents metadata about some path on a remote machine #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] diff --git a/distant-core/src/data/pty.rs b/distant-core/src/data/pty.rs index 2fd57c3..6d6a054 100644 --- a/distant-core/src/data/pty.rs +++ b/distant-core/src/data/pty.rs @@ -1,7 +1,10 @@ +use std::fmt; +use std::num::ParseIntError; +use std::str::FromStr; + use derive_more::{Display, Error}; use portable_pty::PtySize as PortablePtySize; use serde::{Deserialize, Serialize}; -use std::{fmt, num::ParseIntError, str::FromStr}; /// Represents the size associated with a remote PTY #[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] diff --git a/distant-core/src/data/search.rs b/distant-core/src/data/search.rs index ff79ee4..e1060b5 100644 --- a/distant-core/src/data/search.rs +++ b/distant-core/src/data/search.rs @@ -1,6 +1,11 @@ -use super::FileType; +use std::borrow::Cow; +use std::collections::HashSet; +use std::path::PathBuf; +use std::str::FromStr; + use serde::{Deserialize, Serialize}; -use std::{borrow::Cow, collections::HashSet, path::PathBuf, str::FromStr}; + +use super::FileType; /// Id associated with a search pub type SearchId = u32; @@ -380,9 +385,10 @@ mod tests { use super::*; mod search_query_condition { - use super::*; use test_log::test; + use super::*; + #[test] fn to_regex_string_should_convert_to_appropriate_regex_and_escape_as_needed() { assert_eq!( diff --git a/distant-core/src/data/system.rs b/distant-core/src/data/system.rs index ddb0576..48ae816 100644 --- a/distant-core/src/data/system.rs +++ b/distant-core/src/data/system.rs @@ -1,5 +1,7 @@ +use std::env; +use std::path::PathBuf; + use serde::{Deserialize, Serialize}; -use std::{env, path::PathBuf}; /// Represents information about a system #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] diff --git a/distant-core/src/serde_str.rs b/distant-core/src/serde_str.rs index 8898b74..f676236 100644 --- a/distant-core/src/serde_str.rs +++ b/distant-core/src/serde_str.rs @@ -1,8 +1,9 @@ -use serde::{ - de::{Deserializer, Error as SerdeError, Visitor}, - ser::Serializer, -}; -use std::{fmt, marker::PhantomData, str::FromStr}; +use std::fmt; +use std::marker::PhantomData; +use std::str::FromStr; + +use serde::de::{Deserializer, Error as SerdeError, Visitor}; +use serde::ser::Serializer; /// From https://docs.rs/serde_with/1.14.0/src/serde_with/rust.rs.html#90-118 pub fn deserialize_from_str<'de, D, T>(deserializer: D) -> Result diff --git a/distant-core/tests/stress/distant/large_file.rs b/distant-core/tests/stress/distant/large_file.rs index feb69bc..e6b8897 100644 --- a/distant-core/tests/stress/distant/large_file.rs +++ b/distant-core/tests/stress/distant/large_file.rs @@ -1,9 +1,10 @@ -use crate::stress::fixtures::*; use assert_fs::prelude::*; use distant_core::DistantChannelExt; use rstest::*; use test_log::test; +use crate::stress::fixtures::*; + // 64KB is maximum TCP packet size const MAX_TCP_PACKET_BYTES: usize = 65535; diff --git a/distant-core/tests/stress/distant/watch.rs b/distant-core/tests/stress/distant/watch.rs index 1a54bce..ad690ee 100644 --- a/distant-core/tests/stress/distant/watch.rs +++ b/distant-core/tests/stress/distant/watch.rs @@ -1,9 +1,11 @@ -use crate::stress::fixtures::*; use assert_fs::prelude::*; -use distant_core::{data::ChangeKindSet, DistantChannelExt}; +use distant_core::data::ChangeKindSet; +use distant_core::DistantChannelExt; use rstest::*; use test_log::test; +use crate::stress::fixtures::*; + const MAX_FILES: usize = 500; #[rstest] diff --git a/distant-core/tests/stress/fixtures.rs b/distant-core/tests/stress/fixtures.rs index 2e75f6c..25e52ea 100644 --- a/distant-core/tests/stress/fixtures.rs +++ b/distant-core/tests/stress/fixtures.rs @@ -1,11 +1,12 @@ +use std::net::SocketAddr; +use std::time::Duration; + use distant_core::net::client::{Client, TcpConnector}; use distant_core::net::common::authentication::{DummyAuthHandler, Verifier}; use distant_core::net::common::PortRange; use distant_core::net::server::Server; use distant_core::{DistantApiServerHandler, DistantClient, LocalDistantApi}; use rstest::*; -use std::net::SocketAddr; -use std::time::Duration; use tokio::sync::mpsc; pub struct DistantClientCtx { diff --git a/distant-net/src/client.rs b/distant-net/src/client.rs index 7b7faac..2c655ad 100644 --- a/distant-net/src/client.rs +++ b/distant-net/src/client.rs @@ -1,19 +1,18 @@ +use std::ops::{Deref, DerefMut}; +use std::sync::Arc; +use std::time::{Duration, Instant}; +use std::{fmt, io}; + +use log::*; +use serde::de::DeserializeOwned; +use serde::Serialize; +use tokio::sync::{mpsc, oneshot, watch}; +use tokio::task::JoinHandle; + use crate::common::{ Connection, FramedTransport, HeapSecretKey, InmemoryTransport, Interest, Reconnectable, Transport, UntypedRequest, UntypedResponse, }; -use log::*; -use serde::{de::DeserializeOwned, Serialize}; -use std::{ - fmt, io, - ops::{Deref, DerefMut}, - sync::Arc, - time::{Duration, Instant}, -}; -use tokio::{ - sync::{mpsc, oneshot, watch}, - task::JoinHandle, -}; mod builder; pub use builder::*; @@ -644,8 +643,9 @@ mod tests { use crate::common::{Ready, Request, Response, TestTransport}; mod typed { - use super::*; use test_log::test; + + use super::*; type TestClient = Client; fn spawn_test_client( @@ -962,8 +962,9 @@ mod tests { } mod untyped { - use super::*; use test_log::test; + + use super::*; type TestClient = UntypedClient; /// Creates a new test transport whose operations do not panic, but do nothing. diff --git a/distant-net/src/client/builder.rs b/distant-net/src/client/builder.rs index 199c0d3..46a6e08 100644 --- a/distant-net/src/client/builder.rs +++ b/distant-net/src/client/builder.rs @@ -10,14 +10,17 @@ pub use unix::*; #[cfg(windows)] mod windows; +use std::time::Duration; +use std::{convert, io}; + +use async_trait::async_trait; #[cfg(windows)] pub use windows::*; use super::ClientConfig; use crate::client::{Client, UntypedClient}; -use crate::common::{authentication::AuthHandler, Connection, Transport}; -use async_trait::async_trait; -use std::{convert, io, time::Duration}; +use crate::common::authentication::AuthHandler; +use crate::common::{Connection, Transport}; /// Interface that performs the connection to produce a [`Transport`] for use by the [`Client`]. #[async_trait] diff --git a/distant-net/src/client/builder/tcp.rs b/distant-net/src/client/builder/tcp.rs index ae7f345..44d4817 100644 --- a/distant-net/src/client/builder/tcp.rs +++ b/distant-net/src/client/builder/tcp.rs @@ -1,9 +1,11 @@ -use super::Connector; -use crate::common::TcpTransport; -use async_trait::async_trait; use std::io; + +use async_trait::async_trait; use tokio::net::ToSocketAddrs; +use super::Connector; +use crate::common::TcpTransport; + /// Implementation of [`Connector`] to support connecting via TCP. pub struct TcpConnector { addr: T, diff --git a/distant-net/src/client/builder/unix.rs b/distant-net/src/client/builder/unix.rs index b934e28..1d97ba8 100644 --- a/distant-net/src/client/builder/unix.rs +++ b/distant-net/src/client/builder/unix.rs @@ -1,7 +1,10 @@ +use std::io; +use std::path::PathBuf; + +use async_trait::async_trait; + use super::Connector; use crate::common::UnixSocketTransport; -use async_trait::async_trait; -use std::{io, path::PathBuf}; /// Implementation of [`Connector`] to support connecting via a Unix socket. pub struct UnixSocketConnector { diff --git a/distant-net/src/client/builder/windows.rs b/distant-net/src/client/builder/windows.rs index 4b0b0ba..e035ebf 100644 --- a/distant-net/src/client/builder/windows.rs +++ b/distant-net/src/client/builder/windows.rs @@ -1,9 +1,11 @@ -use super::Connector; -use crate::common::WindowsPipeTransport; -use async_trait::async_trait; use std::ffi::OsString; use std::io; +use async_trait::async_trait; + +use super::Connector; +use crate::common::WindowsPipeTransport; + /// Implementation of [`Connector`] to support connecting via a Windows named pipe. pub struct WindowsPipeConnector { addr: OsString, diff --git a/distant-net/src/client/channel.rs b/distant-net/src/client/channel.rs index fb86641..af072bc 100644 --- a/distant-net/src/client/channel.rs +++ b/distant-net/src/client/channel.rs @@ -1,8 +1,14 @@ -use crate::common::{Request, Response, UntypedRequest, UntypedResponse}; +use std::marker::PhantomData; +use std::sync::Weak; +use std::{convert, fmt, io}; + use log::*; -use serde::{de::DeserializeOwned, Serialize}; -use std::{convert, fmt, io, marker::PhantomData, sync::Weak}; -use tokio::{sync::mpsc, time::Duration}; +use serde::de::DeserializeOwned; +use serde::Serialize; +use tokio::sync::mpsc; +use tokio::time::Duration; + +use crate::common::{Request, Response, UntypedRequest, UntypedResponse}; mod mailbox; pub use mailbox::*; @@ -336,11 +342,13 @@ mod tests { use super::*; mod typed { - use super::*; use std::sync::Arc; use std::time::Duration; + use test_log::test; + use super::*; + type TestChannel = Channel; type Setup = ( TestChannel, @@ -446,11 +454,13 @@ mod tests { } mod untyped { - use super::*; use std::sync::Arc; use std::time::Duration; + use test_log::test; + use super::*; + type TestChannel = UntypedChannel; type Setup = ( TestChannel, diff --git a/distant-net/src/client/channel/mailbox.rs b/distant-net/src/client/channel/mailbox.rs index 872bc44..baa0536 100644 --- a/distant-net/src/client/channel/mailbox.rs +++ b/distant-net/src/client/channel/mailbox.rs @@ -1,15 +1,12 @@ -use crate::common::{Id, Response, UntypedResponse}; +use std::collections::HashMap; +use std::sync::{Arc, Weak}; +use std::time::Duration; + use async_trait::async_trait; -use std::{ - collections::HashMap, - sync::{Arc, Weak}, - time::Duration, -}; -use tokio::{ - io, - sync::{mpsc, Mutex, RwLock}, - time, -}; +use tokio::sync::{mpsc, Mutex, RwLock}; +use tokio::{io, time}; + +use crate::common::{Id, Response, UntypedResponse}; #[derive(Clone, Debug)] pub struct PostOffice { diff --git a/distant-net/src/client/config.rs b/distant-net/src/client/config.rs index 2e48cd3..a87a7eb 100644 --- a/distant-net/src/client/config.rs +++ b/distant-net/src/client/config.rs @@ -1,6 +1,7 @@ -use super::ReconnectStrategy; use std::time::Duration; +use super::ReconnectStrategy; + const DEFAULT_SILENCE_DURATION: Duration = Duration::from_secs(20); const MAXIMUM_SILENCE_DURATION: Duration = Duration::from_millis(68719476734); diff --git a/distant-net/src/client/reconnect.rs b/distant-net/src/client/reconnect.rs index 98e5670..6b894b3 100644 --- a/distant-net/src/client/reconnect.rs +++ b/distant-net/src/client/reconnect.rs @@ -1,11 +1,13 @@ -use super::Reconnectable; -use log::*; use std::io; use std::time::Duration; + +use log::*; use strum::Display; use tokio::sync::watch; use tokio::task::JoinHandle; +use super::Reconnectable; + /// Represents a watcher over a [`ConnectionState`]. #[derive(Clone)] pub struct ConnectionWatcher(pub(super) watch::Receiver); diff --git a/distant-net/src/client/shutdown.rs b/distant-net/src/client/shutdown.rs index 3a0fe94..ceb7618 100644 --- a/distant-net/src/client/shutdown.rs +++ b/distant-net/src/client/shutdown.rs @@ -1,6 +1,7 @@ +use std::io; + use async_trait::async_trait; use dyn_clone::DynClone; -use std::io; use tokio::sync::{mpsc, oneshot}; /// Interface representing functionality to shut down an active client. diff --git a/distant-net/src/common/authentication/authenticator.rs b/distant-net/src/common/authentication/authenticator.rs index a37555f..2cd451c 100644 --- a/distant-net/src/common/authentication/authenticator.rs +++ b/distant-net/src/common/authentication/authenticator.rs @@ -1,8 +1,11 @@ -use super::{msg::*, AuthHandler}; -use crate::common::{utils, FramedTransport, Transport}; +use std::io; + use async_trait::async_trait; use log::*; -use std::io; + +use super::msg::*; +use super::AuthHandler; +use crate::common::{utils, FramedTransport, Transport}; /// Represents an interface for authenticating with a server. #[async_trait] @@ -200,11 +203,12 @@ where #[cfg(test)] mod tests { - use super::*; - use crate::common::authentication::AuthMethodHandler; use test_log::test; use tokio::sync::mpsc; + use super::*; + use crate::common::authentication::AuthMethodHandler; + #[async_trait] trait TestAuthHandler { async fn on_initialization( diff --git a/distant-net/src/common/authentication/handler.rs b/distant-net/src/common/authentication/handler.rs index 945bf6d..662f288 100644 --- a/distant-net/src/common/authentication/handler.rs +++ b/distant-net/src/common/authentication/handler.rs @@ -1,9 +1,11 @@ +use std::collections::HashMap; +use std::io; + +use async_trait::async_trait; + use super::msg::*; use crate::common::authentication::Authenticator; use crate::common::HeapSecretKey; -use async_trait::async_trait; -use std::collections::HashMap; -use std::io; mod methods; pub use methods::*; diff --git a/distant-net/src/common/authentication/handler/methods.rs b/distant-net/src/common/authentication/handler/methods.rs index 3fda4a7..5ee35e5 100644 --- a/distant-net/src/common/authentication/handler/methods.rs +++ b/distant-net/src/common/authentication/handler/methods.rs @@ -1,8 +1,10 @@ +use std::io; + +use async_trait::async_trait; + use super::{ Challenge, ChallengeResponse, Error, Info, Verification, VerificationKind, VerificationResponse, }; -use async_trait::async_trait; -use std::io; /// Interface for a handler of authentication requests for a specific authentication method. #[async_trait] diff --git a/distant-net/src/common/authentication/handler/methods/prompt.rs b/distant-net/src/common/authentication/handler/methods/prompt.rs index 901a8aa..57f141b 100644 --- a/distant-net/src/common/authentication/handler/methods/prompt.rs +++ b/distant-net/src/common/authentication/handler/methods/prompt.rs @@ -1,10 +1,12 @@ +use std::io; + +use async_trait::async_trait; +use log::*; + use super::{ AuthMethodHandler, Challenge, ChallengeResponse, Error, Info, Verification, VerificationKind, VerificationResponse, }; -use async_trait::async_trait; -use log::*; -use std::io; /// Blocking implementation of [`AuthMethodHandler`] that uses prompts to communicate challenge & /// verification requests, receiving responses to relay back. diff --git a/distant-net/src/common/authentication/handler/methods/static_key.rs b/distant-net/src/common/authentication/handler/methods/static_key.rs index c6ce17c..f58b07b 100644 --- a/distant-net/src/common/authentication/handler/methods/static_key.rs +++ b/distant-net/src/common/authentication/handler/methods/static_key.rs @@ -1,11 +1,13 @@ +use std::io; + +use async_trait::async_trait; +use log::*; + use super::{ AuthMethodHandler, Challenge, ChallengeResponse, Error, Info, Verification, VerificationResponse, }; use crate::common::HeapSecretKey; -use async_trait::async_trait; -use log::*; -use std::io; /// Implementation of [`AuthMethodHandler`] that answers challenge requests using a static /// [`HeapSecretKey`]. All other portions of method authentication are handled by another @@ -98,9 +100,10 @@ impl AuthMethodHandler for StaticKeyAuthMethodHandler { #[cfg(test)] mod tests { + use test_log::test; + use super::*; use crate::common::authentication::msg::{ErrorKind, Question, VerificationKind}; - use test_log::test; #[test(tokio::test)] async fn on_challenge_should_fail_if_non_key_question_received() { diff --git a/distant-net/src/common/authentication/keychain.rs b/distant-net/src/common/authentication/keychain.rs index 2018d15..8ff6a16 100644 --- a/distant-net/src/common/authentication/keychain.rs +++ b/distant-net/src/common/authentication/keychain.rs @@ -1,8 +1,10 @@ -use crate::common::HeapSecretKey; use std::collections::HashMap; use std::sync::Arc; + use tokio::sync::RwLock; +use crate::common::HeapSecretKey; + /// Represents the result of a request to the database. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum KeychainResult { diff --git a/distant-net/src/common/authentication/methods.rs b/distant-net/src/common/authentication/methods.rs index ee188bf..496d40a 100644 --- a/distant-net/src/common/authentication/methods.rs +++ b/distant-net/src/common/authentication/methods.rs @@ -1,9 +1,13 @@ -use super::{super::HeapSecretKey, msg::*, Authenticator}; -use async_trait::async_trait; -use log::*; use std::collections::HashMap; use std::io; +use async_trait::async_trait; +use log::*; + +use super::super::HeapSecretKey; +use super::msg::*; +use super::Authenticator; + mod none; mod static_key; @@ -113,9 +117,10 @@ pub trait AuthenticationMethod: Send + Sync { #[cfg(test)] mod tests { + use test_log::test; + use super::*; use crate::common::FramedTransport; - use test_log::test; struct SuccessAuthenticationMethod; diff --git a/distant-net/src/common/authentication/methods/none.rs b/distant-net/src/common/authentication/methods/none.rs index 757b479..e9f3057 100644 --- a/distant-net/src/common/authentication/methods/none.rs +++ b/distant-net/src/common/authentication/methods/none.rs @@ -1,7 +1,9 @@ -use super::{AuthenticationMethod, Authenticator}; -use async_trait::async_trait; use std::io; +use async_trait::async_trait; + +use super::{AuthenticationMethod, Authenticator}; + /// Authenticaton method for a static secret key #[derive(Clone, Debug)] pub struct NoneAuthenticationMethod; diff --git a/distant-net/src/common/authentication/methods/static_key.rs b/distant-net/src/common/authentication/methods/static_key.rs index bace4fd..f0d9338 100644 --- a/distant-net/src/common/authentication/methods/static_key.rs +++ b/distant-net/src/common/authentication/methods/static_key.rs @@ -1,7 +1,9 @@ +use std::io; + +use async_trait::async_trait; + use super::{AuthenticationMethod, Authenticator, Challenge, Error, Question}; use crate::common::HeapSecretKey; -use async_trait::async_trait; -use std::io; /// Authenticaton method for a static secret key #[derive(Clone, Debug)] @@ -53,13 +55,12 @@ impl AuthenticationMethod for StaticKeyAuthenticationMethod { #[cfg(test)] mod tests { - use super::*; - use crate::common::{ - authentication::msg::{AuthenticationResponse, ChallengeResponse}, - FramedTransport, - }; use test_log::test; + use super::*; + use crate::common::authentication::msg::{AuthenticationResponse, ChallengeResponse}; + use crate::common::FramedTransport; + #[test(tokio::test)] async fn authenticate_should_fail_if_key_challenge_fails() { let method = StaticKeyAuthenticationMethod::new(b"".to_vec()); diff --git a/distant-net/src/common/authentication/msg.rs b/distant-net/src/common/authentication/msg.rs index 39e38c0..4c300f2 100644 --- a/distant-net/src/common/authentication/msg.rs +++ b/distant-net/src/common/authentication/msg.rs @@ -1,6 +1,7 @@ +use std::collections::HashMap; + use derive_more::{Display, Error, From}; use serde::{Deserialize, Serialize}; -use std::collections::HashMap; /// Represents messages from an authenticator that act as initiators such as providing /// a challenge, verifying information, presenting information, or highlighting an error diff --git a/distant-net/src/common/connection.rs b/distant-net/src/common/connection.rs index ff67daf..8d7ba6d 100644 --- a/distant-net/src/common/connection.rs +++ b/distant-net/src/common/connection.rs @@ -1,16 +1,15 @@ -use super::{ - authentication::{AuthHandler, Authenticate, Keychain, KeychainResult, Verifier}, - Backup, FramedTransport, HeapSecretKey, Reconnectable, Transport, -}; +use std::io; +use std::ops::{Deref, DerefMut}; + use async_trait::async_trait; use log::*; use serde::{Deserialize, Serialize}; -use std::io; -use std::ops::{Deref, DerefMut}; use tokio::sync::oneshot; +use super::authentication::{AuthHandler, Authenticate, Keychain, KeychainResult, Verifier}; #[cfg(test)] use super::InmemoryTransport; +use super::{Backup, FramedTransport, HeapSecretKey, Reconnectable, Transport}; /// Id of the connection pub type ConnectionId = u32; @@ -454,14 +453,15 @@ impl Connection { #[cfg(test)] mod tests { - use super::*; - use crate::common::{ - authentication::{msg::Challenge, Authenticator, DummyAuthHandler}, - Frame, - }; use std::sync::Arc; + use test_log::test; + use super::*; + use crate::common::authentication::msg::Challenge; + use crate::common::authentication::{Authenticator, DummyAuthHandler}; + use crate::common::Frame; + #[test(tokio::test)] async fn client_should_fail_if_codec_handshake_fails() { let (mut t1, t2) = FramedTransport::pair(100); diff --git a/distant-net/src/common/destination.rs b/distant-net/src/common/destination.rs index 1bf3a05..4eaef38 100644 --- a/distant-net/src/common/destination.rs +++ b/distant-net/src/common/destination.rs @@ -1,6 +1,12 @@ +use std::fmt; +use std::hash::Hash; +use std::str::FromStr; + +use serde::de::Deserializer; +use serde::ser::Serializer; +use serde::{Deserialize, Serialize}; + use super::utils::{deserialize_from_str, serialize_to_str}; -use serde::{de::Deserializer, ser::Serializer, Deserialize, Serialize}; -use std::{fmt, hash::Hash, str::FromStr}; mod host; mod parser; diff --git a/distant-net/src/common/destination/host.rs b/distant-net/src/common/destination/host.rs index 49d61f7..2d9bad4 100644 --- a/distant-net/src/common/destination/host.rs +++ b/distant-net/src/common/destination/host.rs @@ -1,11 +1,13 @@ -use super::{deserialize_from_str, serialize_to_str}; +use std::fmt; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; +use std::str::FromStr; + use derive_more::{Display, Error, From}; -use serde::{de::Deserializer, ser::Serializer, Deserialize, Serialize}; -use std::{ - fmt, - net::{IpAddr, Ipv4Addr, Ipv6Addr}, - str::FromStr, -}; +use serde::de::Deserializer; +use serde::ser::Serializer; +use serde::{Deserialize, Serialize}; + +use super::{deserialize_from_str, serialize_to_str}; /// Represents the host of a destination #[derive(Clone, Debug, From, Display, Hash, PartialEq, Eq)] diff --git a/distant-net/src/common/destination/parser.rs b/distant-net/src/common/destination/parser.rs index 0976765..cdb11a2 100644 --- a/distant-net/src/common/destination/parser.rs +++ b/distant-net/src/common/destination/parser.rs @@ -342,9 +342,10 @@ mod tests { } mod parse_host { - use super::*; use std::net::{Ipv4Addr, Ipv6Addr}; + use super::*; + #[test] fn should_fail_if_domain_name_is_invalid() { let _ = parse_host("").unwrap_err(); diff --git a/distant-net/src/common/listener.rs b/distant-net/src/common/listener.rs index dd2ed66..c85bee7 100644 --- a/distant-net/src/common/listener.rs +++ b/distant-net/src/common/listener.rs @@ -1,6 +1,7 @@ -use async_trait::async_trait; use std::io; +use async_trait::async_trait; + mod mapped; pub use mapped::*; diff --git a/distant-net/src/common/listener/mapped.rs b/distant-net/src/common/listener/mapped.rs index 55c4d51..a4ba5c2 100644 --- a/distant-net/src/common/listener/mapped.rs +++ b/distant-net/src/common/listener/mapped.rs @@ -1,7 +1,9 @@ -use super::Listener; -use async_trait::async_trait; use std::io; +use async_trait::async_trait; + +use super::Listener; + /// Represents a [`Listener`] that wraps a different [`Listener`], /// mapping the received connection to something else using the map function pub struct MappedListener diff --git a/distant-net/src/common/listener/mpsc.rs b/distant-net/src/common/listener/mpsc.rs index 05937a4..f3f86de 100644 --- a/distant-net/src/common/listener/mpsc.rs +++ b/distant-net/src/common/listener/mpsc.rs @@ -1,9 +1,11 @@ -use super::Listener; +use std::io; + use async_trait::async_trait; use derive_more::From; -use std::io; use tokio::sync::mpsc; +use super::Listener; + /// Represents a [`Listener`] that uses an [`mpsc::Receiver`] to /// accept new connections #[derive(From)] diff --git a/distant-net/src/common/listener/oneshot.rs b/distant-net/src/common/listener/oneshot.rs index 1db1cd6..37833d4 100644 --- a/distant-net/src/common/listener/oneshot.rs +++ b/distant-net/src/common/listener/oneshot.rs @@ -1,9 +1,11 @@ -use super::Listener; +use std::io; + use async_trait::async_trait; use derive_more::From; -use std::io; use tokio::sync::oneshot; +use super::Listener; + /// Represents a [`Listener`] that only has a single connection #[derive(From)] pub struct OneshotListener { @@ -47,10 +49,11 @@ impl Listener for OneshotListener { #[cfg(test)] mod tests { - use super::*; use test_log::test; use tokio::task::JoinHandle; + use super::*; + #[test(tokio::test)] async fn from_value_should_return_value_on_first_call_to_accept() { let mut listener = OneshotListener::from_value("hello world"); diff --git a/distant-net/src/common/listener/tcp.rs b/distant-net/src/common/listener/tcp.rs index 4160718..0bd4c9f 100644 --- a/distant-net/src/common/listener/tcp.rs +++ b/distant-net/src/common/listener/tcp.rs @@ -1,9 +1,12 @@ -use super::Listener; -use crate::common::{PortRange, TcpTransport}; +use std::net::IpAddr; +use std::{fmt, io}; + use async_trait::async_trait; -use std::{fmt, io, net::IpAddr}; use tokio::net::TcpListener as TokioTcpListener; +use super::Listener; +use crate::common::{PortRange, TcpTransport}; + /// Represents a [`Listener`] for incoming connections over TCP pub struct TcpListener { addr: IpAddr, @@ -64,11 +67,14 @@ impl Listener for TcpListener { #[cfg(test)] mod tests { - use super::*; - use crate::common::TransportExt; use std::net::{Ipv6Addr, SocketAddr}; + use test_log::test; - use tokio::{sync::oneshot, task::JoinHandle}; + use tokio::sync::oneshot; + use tokio::task::JoinHandle; + + use super::*; + use crate::common::TransportExt; #[test(tokio::test)] async fn should_fail_to_bind_if_port_already_bound() { diff --git a/distant-net/src/common/listener/unix.rs b/distant-net/src/common/listener/unix.rs index b46e9a3..aabce9d 100644 --- a/distant-net/src/common/listener/unix.rs +++ b/distant-net/src/common/listener/unix.rs @@ -1,13 +1,13 @@ -use super::Listener; -use crate::common::UnixSocketTransport; +use std::os::unix::fs::PermissionsExt; +use std::path::{Path, PathBuf}; +use std::{fmt, io}; + use async_trait::async_trait; -use std::{ - fmt, io, - os::unix::fs::PermissionsExt, - path::{Path, PathBuf}, -}; use tokio::net::{UnixListener, UnixStream}; +use super::Listener; +use crate::common::UnixSocketTransport; + /// Represents a [`Listener`] for incoming connections over a Unix socket pub struct UnixSocketListener { path: PathBuf, @@ -94,11 +94,13 @@ impl Listener for UnixSocketListener { #[cfg(test)] mod tests { - use super::*; - use crate::common::TransportExt; use tempfile::NamedTempFile; use test_log::test; - use tokio::{sync::oneshot, task::JoinHandle}; + use tokio::sync::oneshot; + use tokio::task::JoinHandle; + + use super::*; + use crate::common::TransportExt; #[test(tokio::test)] async fn should_succeed_to_bind_if_file_exists_at_path_but_nothing_listening() { diff --git a/distant-net/src/common/listener/windows.rs b/distant-net/src/common/listener/windows.rs index e0a12c6..be58cf3 100644 --- a/distant-net/src/common/listener/windows.rs +++ b/distant-net/src/common/listener/windows.rs @@ -1,12 +1,12 @@ -use super::Listener; -use crate::common::{NamedPipe, WindowsPipeTransport}; +use std::ffi::{OsStr, OsString}; +use std::{fmt, io, mem}; + use async_trait::async_trait; -use std::{ - ffi::{OsStr, OsString}, - fmt, io, mem, -}; use tokio::net::windows::named_pipe::{NamedPipeServer, ServerOptions}; +use super::Listener; +use crate::common::{NamedPipe, WindowsPipeTransport}; + /// Represents a [`Listener`] for incoming connections over a named windows pipe pub struct WindowsPipeListener { addr: OsString, @@ -66,10 +66,12 @@ impl Listener for WindowsPipeListener { #[cfg(test)] mod tests { + use test_log::test; + use tokio::sync::oneshot; + use tokio::task::JoinHandle; + use super::*; use crate::common::TransportExt; - use test_log::test; - use tokio::{sync::oneshot, task::JoinHandle}; #[test(tokio::test)] async fn should_fail_to_bind_if_pipe_already_bound() { diff --git a/distant-net/src/common/map.rs b/distant-net/src/common/map.rs index 6c0acbb..68b9b72 100644 --- a/distant-net/src/common/map.rs +++ b/distant-net/src/common/map.rs @@ -1,13 +1,15 @@ -use crate::common::utils::{deserialize_from_str, serialize_to_str}; +use std::collections::hash_map::Entry; +use std::collections::HashMap; +use std::fmt; +use std::ops::{Deref, DerefMut}; +use std::str::FromStr; + use derive_more::{Display, Error, From, IntoIterator}; -use serde::{de::Deserializer, ser::Serializer, Deserialize, Serialize}; -use std::{ - collections::hash_map::Entry, - collections::HashMap, - fmt, - ops::{Deref, DerefMut}, - str::FromStr, -}; +use serde::de::Deserializer; +use serde::ser::Serializer; +use serde::{Deserialize, Serialize}; + +use crate::common::utils::{deserialize_from_str, serialize_to_str}; /// Contains map information for connections and other use cases #[derive(Clone, Debug, From, IntoIterator, PartialEq, Eq)] diff --git a/distant-net/src/common/packet/request.rs b/distant-net/src/common/packet/request.rs index b7b950a..9d2f3e9 100644 --- a/distant-net/src/common/packet/request.rs +++ b/distant-net/src/common/packet/request.rs @@ -1,8 +1,12 @@ +use std::borrow::Cow; +use std::{io, str}; + +use derive_more::{Display, Error}; +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; + use super::{parse_msg_pack_str, write_str_msg_pack, Id}; use crate::common::utils; -use derive_more::{Display, Error}; -use serde::{de::DeserializeOwned, Deserialize, Serialize}; -use std::{borrow::Cow, io, str}; /// Represents a request to send #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] @@ -195,9 +199,10 @@ impl<'a> UntypedRequest<'a> { #[cfg(test)] mod tests { - use super::*; use test_log::test; + use super::*; + const TRUE_BYTE: u8 = 0xc3; const NEVER_USED_BYTE: u8 = 0xc1; diff --git a/distant-net/src/common/packet/response.rs b/distant-net/src/common/packet/response.rs index d50e36f..e5d38d8 100644 --- a/distant-net/src/common/packet/response.rs +++ b/distant-net/src/common/packet/response.rs @@ -1,8 +1,12 @@ +use std::borrow::Cow; +use std::io; + +use derive_more::{Display, Error}; +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; + use super::{parse_msg_pack_str, write_str_msg_pack, Id}; use crate::common::utils; -use derive_more::{Display, Error}; -use serde::{de::DeserializeOwned, Deserialize, Serialize}; -use std::{borrow::Cow, io}; /// Represents a response received related to some response #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] @@ -233,9 +237,10 @@ impl<'a> UntypedResponse<'a> { #[cfg(test)] mod tests { - use super::*; use test_log::test; + use super::*; + const TRUE_BYTE: u8 = 0xc3; const NEVER_USED_BYTE: u8 = 0xc1; diff --git a/distant-net/src/common/port.rs b/distant-net/src/common/port.rs index 09066d2..fd100ac 100644 --- a/distant-net/src/common/port.rs +++ b/distant-net/src/common/port.rs @@ -1,11 +1,10 @@ +use std::fmt; +use std::net::{IpAddr, SocketAddr}; +use std::ops::RangeInclusive; +use std::str::FromStr; + use derive_more::Display; use serde::{de, Deserialize, Serialize}; -use std::{ - fmt, - net::{IpAddr, SocketAddr}, - ops::RangeInclusive, - str::FromStr, -}; /// Represents some range of ports #[derive(Copy, Clone, Debug, Display, PartialEq, Eq)] @@ -71,8 +70,8 @@ impl From> for PortRange { } impl<'a> IntoIterator for &'a PortRange { - type Item = u16; type IntoIter = RangeInclusive; + type Item = u16; fn into_iter(self) -> Self::IntoIter { self.start..=self.end.unwrap_or(self.start) @@ -80,8 +79,8 @@ impl<'a> IntoIterator for &'a PortRange { } impl IntoIterator for PortRange { - type Item = u16; type IntoIter = RangeInclusive; + type Item = u16; fn into_iter(self) -> Self::IntoIter { self.start..=self.end.unwrap_or(self.start) diff --git a/distant-net/src/common/transport.rs b/distant-net/src/common/transport.rs index a1a1b6d..87be088 100644 --- a/distant-net/src/common/transport.rs +++ b/distant-net/src/common/transport.rs @@ -1,5 +1,7 @@ +use std::time::Duration; +use std::{fmt, io}; + use async_trait::async_trait; -use std::{fmt, io, time::Duration}; mod framed; pub use framed::*; @@ -25,11 +27,10 @@ pub use unix::*; #[cfg(windows)] mod windows; +pub use tokio::io::{Interest, Ready}; #[cfg(windows)] pub use windows::*; -pub use tokio::io::{Interest, Ready}; - /// Duration to wait after WouldBlock received during looping operations like `read_exact`. const SLEEP_DURATION: Duration = Duration::from_millis(1); @@ -270,9 +271,10 @@ impl TransportExt for T { #[cfg(test)] mod tests { - use super::*; use test_log::test; + use super::*; + #[test(tokio::test)] async fn read_exact_should_fail_if_try_read_encounters_error_other_than_would_block() { let transport = TestTransport { diff --git a/distant-net/src/common/transport/framed.rs b/distant-net/src/common/transport/framed.rs index e173b22..39330d4 100644 --- a/distant-net/src/common/transport/framed.rs +++ b/distant-net/src/common/transport/framed.rs @@ -1,10 +1,15 @@ -use super::{InmemoryTransport, Interest, Ready, Reconnectable, Transport}; -use crate::common::utils; +use std::future::Future; +use std::time::Duration; +use std::{fmt, io}; + use async_trait::async_trait; use bytes::{Buf, BytesMut}; use log::*; -use serde::{de::DeserializeOwned, Deserialize, Serialize}; -use std::{fmt, future::Future, io, time::Duration}; +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; + +use super::{InmemoryTransport, Interest, Ready, Reconnectable, Transport}; +use crate::common::utils; mod backup; mod codec; @@ -585,6 +590,7 @@ impl FramedTransport { pub async fn client_handshake(&mut self) -> io::Result<()> { self.handshake(Handshake::client()).await } + /// Shorthand for creating a [`FramedTransport`] with a [`PlainCodec`] and then immediately /// performing a [`server_handshake`], returning the updated [`FramedTransport`] on success. /// @@ -905,11 +911,12 @@ impl FramedTransport { #[cfg(test)] mod tests { - use super::*; - use crate::common::TestTransport; use bytes::BufMut; use test_log::test; + use super::*; + use crate::common::TestTransport; + /// Codec that always succeeds without altering the frame #[derive(Clone, Debug, PartialEq, Eq)] struct OkCodec; diff --git a/distant-net/src/common/transport/framed/backup.rs b/distant-net/src/common/transport/framed/backup.rs index 3888c96..8900829 100644 --- a/distant-net/src/common/transport/framed/backup.rs +++ b/distant-net/src/common/transport/framed/backup.rs @@ -1,6 +1,7 @@ -use super::{Frame, OwnedFrame}; use std::collections::VecDeque; +use super::{Frame, OwnedFrame}; + /// Maximum size (in bytes) for saved frames (256MiB) const MAX_BACKUP_SIZE: usize = 256 * 1024 * 1024; diff --git a/distant-net/src/common/transport/framed/codec.rs b/distant-net/src/common/transport/framed/codec.rs index 8aec343..77c0e5d 100644 --- a/distant-net/src/common/transport/framed/codec.rs +++ b/distant-net/src/common/transport/framed/codec.rs @@ -1,7 +1,9 @@ -use super::Frame; -use dyn_clone::DynClone; use std::io; +use dyn_clone::DynClone; + +use super::Frame; + mod chain; mod compression; mod encryption; diff --git a/distant-net/src/common/transport/framed/codec/chain.rs b/distant-net/src/common/transport/framed/codec/chain.rs index 1148bd2..232039d 100644 --- a/distant-net/src/common/transport/framed/codec/chain.rs +++ b/distant-net/src/common/transport/framed/codec/chain.rs @@ -1,6 +1,7 @@ -use super::{Codec, Frame}; use std::io; +use super::{Codec, Frame}; + /// Represents a codec that chains together other codecs such that encoding will call the encode /// methods of the underlying, chained codecs from left-to-right and decoding will call the decode /// methods in reverse order @@ -59,9 +60,10 @@ where #[cfg(test)] mod tests { - use super::*; use test_log::test; + use super::*; + #[derive(Copy, Clone)] struct TestCodec<'a> { msg: &'a str, diff --git a/distant-net/src/common/transport/framed/codec/compression.rs b/distant-net/src/common/transport/framed/codec/compression.rs index fbb40ea..b092a5b 100644 --- a/distant-net/src/common/transport/framed/codec/compression.rs +++ b/distant-net/src/common/transport/framed/codec/compression.rs @@ -1,10 +1,12 @@ -use super::{Codec, Frame}; -use flate2::{ - bufread::{DeflateDecoder, DeflateEncoder, GzDecoder, GzEncoder, ZlibDecoder, ZlibEncoder}, - Compression, +use std::io::{self, Read}; + +use flate2::bufread::{ + DeflateDecoder, DeflateEncoder, GzDecoder, GzEncoder, ZlibDecoder, ZlibEncoder, }; +use flate2::Compression; use serde::{Deserialize, Serialize}; -use std::io::{self, Read}; + +use super::{Codec, Frame}; /// Represents the level of compression to apply to data #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] @@ -28,14 +30,12 @@ pub enum CompressionLevel { } impl CompressionLevel { - /// Applies no compression - pub const NONE: Self = Self::Zero; - - /// Applies fastest compression - pub const FAST: Self = Self::One; - /// Applies best compression to reduce size (slowest) pub const BEST: Self = Self::Nine; + /// Applies fastest compression + pub const FAST: Self = Self::One; + /// Applies no compression + pub const NONE: Self = Self::Zero; } impl Default for CompressionLevel { @@ -186,9 +186,10 @@ impl Codec for CompressionCodec { #[cfg(test)] mod tests { - use super::*; use test_log::test; + use super::*; + #[test] fn encode_should_apply_appropriate_compression_algorithm() { // Encode using DEFLATE and verify that the compression was as expected by decompressing diff --git a/distant-net/src/common/transport/framed/codec/encryption.rs b/distant-net/src/common/transport/framed/codec/encryption.rs index 8d5eac1..9ac553a 100644 --- a/distant-net/src/common/transport/framed/codec/encryption.rs +++ b/distant-net/src/common/transport/framed/codec/encryption.rs @@ -1,7 +1,9 @@ -use super::{Codec, Frame}; -use derive_more::Display; use std::{fmt, io}; +use derive_more::Display; + +use super::{Codec, Frame}; + mod key; pub use key::*; @@ -134,7 +136,8 @@ impl Codec for EncryptionCodec { Ok(match self { Self::XChaCha20Poly1305 { cipher } => { - use chacha20poly1305::{aead::Aead, XNonce}; + use chacha20poly1305::aead::Aead; + use chacha20poly1305::XNonce; let item = frame.into_item(); let nonce = XNonce::from_slice(&nonce_bytes); @@ -165,7 +168,8 @@ impl Codec for EncryptionCodec { // of the frame to tease out the decrypted frame item let item = match self { Self::XChaCha20Poly1305 { cipher } => { - use chacha20poly1305::{aead::Aead, XNonce}; + use chacha20poly1305::aead::Aead; + use chacha20poly1305::XNonce; let nonce = XNonce::from_slice(&frame.as_item()[..nonce_size]); cipher .decrypt(nonce, &frame.as_item()[nonce_size..]) @@ -179,9 +183,10 @@ impl Codec for EncryptionCodec { #[cfg(test)] mod tests { - use super::*; use test_log::test; + use super::*; + #[test] fn encode_should_build_a_frame_containing_a_length_nonce_and_ciphertext() { let ty = EncryptionType::XChaCha20Poly1305; @@ -198,7 +203,8 @@ mod tests { // Manually build our key & cipher so we can decrypt the frame manually to ensure it is // correct let item = { - use chacha20poly1305::{aead::Aead, KeyInit, XChaCha20Poly1305, XNonce}; + use chacha20poly1305::aead::Aead; + use chacha20poly1305::{KeyInit, XChaCha20Poly1305, XNonce}; let cipher = XChaCha20Poly1305::new_from_slice(&key).unwrap(); cipher .decrypt(XNonce::from_slice(nonce), ciphertext) diff --git a/distant-net/src/common/transport/framed/codec/encryption/key.rs b/distant-net/src/common/transport/framed/codec/encryption/key.rs index f1e47da..d8eafc3 100644 --- a/distant-net/src/common/transport/framed/codec/encryption/key.rs +++ b/distant-net/src/common/transport/framed/codec/encryption/key.rs @@ -1,6 +1,9 @@ +use std::fmt; +use std::str::FromStr; + use derive_more::{Display, Error}; -use rand::{rngs::OsRng, RngCore}; -use std::{fmt, str::FromStr}; +use rand::rngs::OsRng; +use rand::RngCore; #[derive(Debug, Display, Error)] pub struct SecretKeyError; @@ -287,9 +290,10 @@ impl PartialEq for &str { #[cfg(test)] mod tests { - use super::*; use test_log::test; + use super::*; + #[test] fn secret_key_should_be_able_to_be_generated() { SecretKey::<0>::generate().unwrap_err(); diff --git a/distant-net/src/common/transport/framed/codec/plain.rs b/distant-net/src/common/transport/framed/codec/plain.rs index d8c180b..9a5295a 100644 --- a/distant-net/src/common/transport/framed/codec/plain.rs +++ b/distant-net/src/common/transport/framed/codec/plain.rs @@ -1,6 +1,7 @@ -use super::{Codec, Frame}; use std::io; +use super::{Codec, Frame}; + /// Represents a codec that does not alter the frame (synonymous with "plain text") #[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] pub struct PlainCodec; diff --git a/distant-net/src/common/transport/framed/codec/predicate.rs b/distant-net/src/common/transport/framed/codec/predicate.rs index e4e744c..fd529e5 100644 --- a/distant-net/src/common/transport/framed/codec/predicate.rs +++ b/distant-net/src/common/transport/framed/codec/predicate.rs @@ -1,5 +1,7 @@ +use std::io; +use std::sync::Arc; + use super::{Codec, Frame}; -use std::{io, sync::Arc}; /// Represents a codec that invokes one of two codecs based on the given predicate #[derive(Debug, Default, PartialEq, Eq)] @@ -85,9 +87,10 @@ where #[cfg(test)] mod tests { - use super::*; use test_log::test; + use super::*; + #[derive(Copy, Clone)] struct TestCodec<'a> { msg: &'a str, diff --git a/distant-net/src/common/transport/framed/exchange.rs b/distant-net/src/common/transport/framed/exchange.rs index 4ef88fd..30dad35 100644 --- a/distant-net/src/common/transport/framed/exchange.rs +++ b/distant-net/src/common/transport/framed/exchange.rs @@ -1,8 +1,12 @@ -use super::SecretKey32; -use p256::{ecdh::EphemeralSecret, PublicKey}; +use std::convert::TryFrom; +use std::io; + +use p256::ecdh::EphemeralSecret; +use p256::PublicKey; use rand::rngs::OsRng; use sha2::Sha256; -use std::{convert::TryFrom, io}; + +use super::SecretKey32; mod pkb; pub use pkb::PublicKeyBytes; diff --git a/distant-net/src/common/transport/framed/exchange/pkb.rs b/distant-net/src/common/transport/framed/exchange/pkb.rs index f896dc3..018a3be 100644 --- a/distant-net/src/common/transport/framed/exchange/pkb.rs +++ b/distant-net/src/common/transport/framed/exchange/pkb.rs @@ -1,6 +1,8 @@ +use std::convert::TryFrom; +use std::io; + use p256::{EncodedPoint, PublicKey}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; -use std::{convert::TryFrom, io}; /// Represents a wrapper around [`EncodedPoint`], and exists to /// fix an issue with [`serde`] deserialization failing when diff --git a/distant-net/src/common/transport/framed/exchange/salt.rs b/distant-net/src/common/transport/framed/exchange/salt.rs index 11f9826..cbed5a7 100644 --- a/distant-net/src/common/transport/framed/exchange/salt.rs +++ b/distant-net/src/common/transport/framed/exchange/salt.rs @@ -1,11 +1,11 @@ -use rand::{rngs::OsRng, RngCore}; +use std::convert::{TryFrom, TryInto}; +use std::ops::BitXor; +use std::str::FromStr; +use std::{fmt, io}; + +use rand::rngs::OsRng; +use rand::RngCore; use serde::{Deserialize, Deserializer, Serialize, Serializer}; -use std::{ - convert::{TryFrom, TryInto}, - fmt, io, - ops::BitXor, - str::FromStr, -}; /// Friendly wrapper around a 32-byte array representing a salt #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] diff --git a/distant-net/src/common/transport/framed/frame.rs b/distant-net/src/common/transport/framed/frame.rs index b92b96b..f7578c4 100644 --- a/distant-net/src/common/transport/framed/frame.rs +++ b/distant-net/src/common/transport/framed/frame.rs @@ -1,6 +1,7 @@ -use bytes::{Buf, BufMut, BytesMut}; use std::borrow::Cow; +use bytes::{Buf, BufMut, BytesMut}; + /// Represents a frame whose lifetime is static pub type OwnedFrame = Frame<'static>; @@ -226,9 +227,10 @@ impl<'a, const N: usize> PartialEq<&'a [u8; N]> for Frame<'_> { #[cfg(test)] mod tests { - use super::*; use test_log::test; + use super::*; + #[test] fn write_should_succeed_when_item_is_zero_bytes() { let frame = Frame::new(&[]); diff --git a/distant-net/src/common/transport/inmemory.rs b/distant-net/src/common/transport/inmemory.rs index 5d5ffdc..0034cd6 100644 --- a/distant-net/src/common/transport/inmemory.rs +++ b/distant-net/src/common/transport/inmemory.rs @@ -1,13 +1,11 @@ -use super::{Interest, Ready, Reconnectable, Transport}; +use std::io; +use std::sync::{Mutex, MutexGuard}; + use async_trait::async_trait; -use std::{ - io, - sync::{Mutex, MutexGuard}, -}; -use tokio::sync::mpsc::{ - self, - error::{TryRecvError, TrySendError}, -}; +use tokio::sync::mpsc::error::{TryRecvError, TrySendError}; +use tokio::sync::mpsc::{self}; + +use super::{Interest, Ready, Reconnectable, Transport}; /// Represents a [`Transport`] comprised of two inmemory channels #[derive(Debug)] @@ -202,9 +200,10 @@ fn copy_and_store( #[cfg(test)] mod tests { + use test_log::test; + use super::*; use crate::common::TransportExt; - use test_log::test; #[test] fn is_rx_closed_should_properly_reflect_if_internal_rx_channel_is_closed() { diff --git a/distant-net/src/common/transport/tcp.rs b/distant-net/src/common/transport/tcp.rs index 86c833c..37558cc 100644 --- a/distant-net/src/common/transport/tcp.rs +++ b/distant-net/src/common/transport/tcp.rs @@ -1,8 +1,11 @@ -use super::{Interest, Ready, Reconnectable, Transport}; +use std::net::IpAddr; +use std::{fmt, io}; + use async_trait::async_trait; -use std::{fmt, io, net::IpAddr}; use tokio::net::{TcpStream, ToSocketAddrs}; +use super::{Interest, Ready, Reconnectable, Transport}; + /// Represents a [`Transport`] that leverages a TCP stream pub struct TcpTransport { pub(crate) addr: IpAddr, @@ -68,11 +71,15 @@ impl Transport for TcpTransport { #[cfg(test)] mod tests { - use super::*; - use crate::common::TransportExt; use std::net::{Ipv6Addr, SocketAddr}; + use test_log::test; - use tokio::{net::TcpListener, sync::oneshot, task::JoinHandle}; + use tokio::net::TcpListener; + use tokio::sync::oneshot; + use tokio::task::JoinHandle; + + use super::*; + use crate::common::TransportExt; async fn find_ephemeral_addr() -> SocketAddr { // Start a listener on a distinct port, get its port, and kill it diff --git a/distant-net/src/common/transport/test.rs b/distant-net/src/common/transport/test.rs index 0b28bf2..930ebc8 100644 --- a/distant-net/src/common/transport/test.rs +++ b/distant-net/src/common/transport/test.rs @@ -1,7 +1,9 @@ -use super::{Interest, Ready, Reconnectable, Transport}; -use async_trait::async_trait; use std::{fmt, io}; +use async_trait::async_trait; + +use super::{Interest, Ready, Reconnectable, Transport}; + pub type TryReadFn = Box io::Result + Send + Sync>; pub type TryWriteFn = Box io::Result + Send + Sync>; pub type ReadyFn = Box io::Result + Send + Sync>; diff --git a/distant-net/src/common/transport/unix.rs b/distant-net/src/common/transport/unix.rs index 0fe496f..bc54a13 100644 --- a/distant-net/src/common/transport/unix.rs +++ b/distant-net/src/common/transport/unix.rs @@ -1,11 +1,11 @@ -use super::{Interest, Ready, Reconnectable, Transport}; +use std::path::{Path, PathBuf}; +use std::{fmt, io}; + use async_trait::async_trait; -use std::{ - fmt, io, - path::{Path, PathBuf}, -}; use tokio::net::UnixStream; +use super::{Interest, Ready, Reconnectable, Transport}; + /// Represents a [`Transport`] that leverages a Unix socket pub struct UnixSocketTransport { pub(crate) path: PathBuf, @@ -61,16 +61,15 @@ impl Transport for UnixSocketTransport { #[cfg(test)] mod tests { - use super::*; - use crate::common::TransportExt; use tempfile::NamedTempFile; use test_log::test; - use tokio::{ - io::{AsyncReadExt, AsyncWriteExt}, - net::UnixListener, - sync::oneshot, - task::JoinHandle, - }; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + use tokio::net::UnixListener; + use tokio::sync::oneshot; + use tokio::task::JoinHandle; + + use super::*; + use crate::common::TransportExt; async fn start_and_run_server(tx: oneshot::Sender) -> io::Result<()> { // Generate a socket path and delete the file after so there is nothing there diff --git a/distant-net/src/common/transport/windows.rs b/distant-net/src/common/transport/windows.rs index 7bd902d..1ea3e57 100644 --- a/distant-net/src/common/transport/windows.rs +++ b/distant-net/src/common/transport/windows.rs @@ -1,9 +1,9 @@ -use super::{Interest, Ready, Reconnectable, Transport}; +use std::ffi::{OsStr, OsString}; +use std::{fmt, io}; + use async_trait::async_trait; -use std::{ - ffi::{OsStr, OsString}, - fmt, io, -}; + +use super::{Interest, Ready, Reconnectable, Transport}; mod pipe; pub use pipe::NamedPipe; @@ -87,14 +87,13 @@ impl Transport for WindowsPipeTransport { #[cfg(test)] mod tests { + use test_log::test; + use tokio::net::windows::named_pipe::{NamedPipeServer, ServerOptions}; + use tokio::sync::oneshot; + use tokio::task::JoinHandle; + use super::*; use crate::common::TransportExt; - use test_log::test; - use tokio::{ - net::windows::named_pipe::{NamedPipeServer, ServerOptions}, - sync::oneshot, - task::JoinHandle, - }; async fn start_and_run_server(tx: oneshot::Sender) -> io::Result<()> { let pipe = start_server(tx).await?; diff --git a/distant-net/src/common/transport/windows/pipe.rs b/distant-net/src/common/transport/windows/pipe.rs index 331bfad..935ba4c 100644 --- a/distant-net/src/common/transport/windows/pipe.rs +++ b/distant-net/src/common/transport/windows/pipe.rs @@ -1,5 +1,8 @@ +use std::ffi::OsStr; +use std::io; +use std::time::Duration; + use derive_more::{From, TryInto}; -use std::{ffi::OsStr, io, time::Duration}; use tokio::net::windows::named_pipe::{ClientOptions, NamedPipeClient, NamedPipeServer}; // Equivalent to winapi::shared::winerror::ERROR_PIPE_BUSY diff --git a/distant-net/src/common/utils.rs b/distant-net/src/common/utils.rs index ce7d671..416c960 100644 --- a/distant-net/src/common/utils.rs +++ b/distant-net/src/common/utils.rs @@ -1,10 +1,14 @@ -use serde::{ - de::{DeserializeOwned, Deserializer, Error as SerdeError, Visitor}, - ser::Serializer, - Serialize, -}; -use std::{fmt, future::Future, io, marker::PhantomData, str::FromStr, time::Duration}; -use tokio::{sync::mpsc, task::JoinHandle}; +use std::future::Future; +use std::marker::PhantomData; +use std::str::FromStr; +use std::time::Duration; +use std::{fmt, io}; + +use serde::de::{DeserializeOwned, Deserializer, Error as SerdeError, Visitor}; +use serde::ser::Serializer; +use serde::Serialize; +use tokio::sync::mpsc; +use tokio::task::JoinHandle; pub fn serialize_to_vec(value: &T) -> io::Result> { rmp_serde::encode::to_vec_named(value) @@ -142,9 +146,10 @@ mod tests { use super::*; mod timer { - use super::*; use test_log::test; + use super::*; + #[test(tokio::test)] async fn should_not_invoke_callback_regardless_of_time_if_not_started() { let timer = Timer::new(Duration::default(), async {}); diff --git a/distant-net/src/lib.rs b/distant-net/src/lib.rs index f23a7c8..f153f79 100644 --- a/distant-net/src/lib.rs +++ b/distant-net/src/lib.rs @@ -5,6 +5,4 @@ pub mod server; pub use client::{Client, ReconnectStrategy}; pub use server::Server; - -pub use log; -pub use paste; +pub use {log, paste}; diff --git a/distant-net/src/manager/client.rs b/distant-net/src/manager/client.rs index 4075929..f1cde90 100644 --- a/distant-net/src/manager/client.rs +++ b/distant-net/src/manager/client.rs @@ -1,19 +1,15 @@ -use crate::{ - client::Client, - common::{ - authentication::{ - msg::{Authentication, AuthenticationResponse}, - AuthHandler, - }, - ConnectionId, Destination, Map, Request, - }, - manager::data::{ - ConnectionInfo, ConnectionList, ManagerCapabilities, ManagerRequest, ManagerResponse, - }, -}; -use log::*; use std::io; +use log::*; + +use crate::client::Client; +use crate::common::authentication::msg::{Authentication, AuthenticationResponse}; +use crate::common::authentication::AuthHandler; +use crate::common::{ConnectionId, Destination, Map, Request}; +use crate::manager::data::{ + ConnectionInfo, ConnectionList, ManagerCapabilities, ManagerRequest, ManagerResponse, +}; + mod channel; pub use channel::*; diff --git a/distant-net/src/manager/client/channel.rs b/distant-net/src/manager/client/channel.rs index 7271542..66e27d0 100644 --- a/distant-net/src/manager/client/channel.rs +++ b/distant-net/src/manager/client/channel.rs @@ -1,16 +1,15 @@ -use crate::{ - client::{Client, ClientConfig, UntypedClient}, - common::{ConnectionId, FramedTransport, InmemoryTransport, UntypedRequest}, - manager::data::{ManagerRequest, ManagerResponse}, -}; +use std::io; +use std::ops::{Deref, DerefMut}; + use log::*; -use serde::{de::DeserializeOwned, Serialize}; -use std::{ - io, - ops::{Deref, DerefMut}, -}; +use serde::de::DeserializeOwned; +use serde::Serialize; use tokio::task::JoinHandle; +use crate::client::{Client, ClientConfig, UntypedClient}; +use crate::common::{ConnectionId, FramedTransport, InmemoryTransport, UntypedRequest}; +use crate::manager::data::{ManagerRequest, ManagerResponse}; + /// Represents a raw channel between a manager client and server. Underneath, this routes incoming /// and outgoing data from a proxied server to an inmemory transport. pub struct RawChannel { diff --git a/distant-net/src/manager/data/capabilities.rs b/distant-net/src/manager/data/capabilities.rs index 43a55c0..3d490a4 100644 --- a/distant-net/src/manager/data/capabilities.rs +++ b/distant-net/src/manager/data/capabilities.rs @@ -1,15 +1,15 @@ -use super::ManagerCapabilityKind; +use std::cmp::Ordering; +use std::collections::HashSet; +use std::hash::{Hash, Hasher}; +use std::ops::{BitAnd, BitOr, BitXor}; +use std::str::FromStr; + use derive_more::{From, Into, IntoIterator}; use serde::{Deserialize, Serialize}; -use std::{ - cmp::Ordering, - collections::HashSet, - hash::{Hash, Hasher}, - ops::{BitAnd, BitOr, BitXor}, - str::FromStr, -}; use strum::{EnumMessage, IntoEnumIterator}; +use super::ManagerCapabilityKind; + /// Set of supported capabilities for a manager #[derive(Clone, Debug, From, Into, PartialEq, Eq, IntoIterator, Serialize, Deserialize)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] diff --git a/distant-net/src/manager/data/info.rs b/distant-net/src/manager/data/info.rs index 10a2624..b719334 100644 --- a/distant-net/src/manager/data/info.rs +++ b/distant-net/src/manager/data/info.rs @@ -1,6 +1,7 @@ -use crate::common::{ConnectionId, Destination, Map}; use serde::{Deserialize, Serialize}; +use crate::common::{ConnectionId, Destination, Map}; + /// Information about a specific connection #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct ConnectionInfo { diff --git a/distant-net/src/manager/data/list.rs b/distant-net/src/manager/data/list.rs index e3fc754..0c1eee6 100644 --- a/distant-net/src/manager/data/list.rs +++ b/distant-net/src/manager/data/list.rs @@ -1,10 +1,10 @@ -use crate::common::{ConnectionId, Destination}; +use std::collections::HashMap; +use std::ops::{Deref, DerefMut, Index, IndexMut}; + use derive_more::IntoIterator; use serde::{Deserialize, Serialize}; -use std::{ - collections::HashMap, - ops::{Deref, DerefMut, Index, IndexMut}, -}; + +use crate::common::{ConnectionId, Destination}; /// Represents a list of information about active connections #[derive(Clone, Debug, PartialEq, Eq, IntoIterator, Serialize, Deserialize)] diff --git a/distant-net/src/manager/data/request.rs b/distant-net/src/manager/data/request.rs index aab5b60..74ab8fd 100644 --- a/distant-net/src/manager/data/request.rs +++ b/distant-net/src/manager/data/request.rs @@ -1,11 +1,11 @@ -use super::{ManagerAuthenticationId, ManagerChannelId}; -use crate::common::{ - authentication::msg::AuthenticationResponse, ConnectionId, Destination, Map, UntypedRequest, -}; use derive_more::IsVariant; use serde::{Deserialize, Serialize}; use strum::{AsRefStr, EnumDiscriminants, EnumIter, EnumMessage, EnumString}; +use super::{ManagerAuthenticationId, ManagerChannelId}; +use crate::common::authentication::msg::AuthenticationResponse; +use crate::common::{ConnectionId, Destination, Map, UntypedRequest}; + #[allow(clippy::large_enum_variant)] #[derive(Clone, Debug, EnumDiscriminants, Serialize, Deserialize)] #[strum_discriminants(derive( diff --git a/distant-net/src/manager/data/response.rs b/distant-net/src/manager/data/response.rs index e69289b..5fd566a 100644 --- a/distant-net/src/manager/data/response.rs +++ b/distant-net/src/manager/data/response.rs @@ -1,10 +1,10 @@ +use serde::{Deserialize, Serialize}; + use super::{ ConnectionInfo, ConnectionList, ManagerAuthenticationId, ManagerCapabilities, ManagerChannelId, }; -use crate::common::{ - authentication::msg::Authentication, ConnectionId, Destination, UntypedResponse, -}; -use serde::{Deserialize, Serialize}; +use crate::common::authentication::msg::Authentication; +use crate::common::{ConnectionId, Destination, UntypedResponse}; #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case", deny_unknown_fields, tag = "type")] diff --git a/distant-net/src/manager/server.rs b/distant-net/src/manager/server.rs index ab1cd1c..a05f821 100644 --- a/distant-net/src/manager/server.rs +++ b/distant-net/src/manager/server.rs @@ -1,16 +1,19 @@ -use crate::{ - common::{authentication::msg::AuthenticationResponse, ConnectionId, Destination, Map}, - manager::{ - ConnectionInfo, ConnectionList, ManagerAuthenticationId, ManagerCapabilities, - ManagerChannelId, ManagerRequest, ManagerResponse, - }, - server::{Server, ServerCtx, ServerHandler}, -}; +use std::collections::HashMap; +use std::io; +use std::sync::Arc; + use async_trait::async_trait; use log::*; -use std::{collections::HashMap, io, sync::Arc}; use tokio::sync::{oneshot, RwLock}; +use crate::common::authentication::msg::AuthenticationResponse; +use crate::common::{ConnectionId, Destination, Map}; +use crate::manager::{ + ConnectionInfo, ConnectionList, ManagerAuthenticationId, ManagerCapabilities, ManagerChannelId, + ManagerRequest, ManagerResponse, +}; +use crate::server::{Server, ServerCtx, ServerHandler}; + mod authentication; pub use authentication::*; @@ -183,9 +186,9 @@ pub struct DistantManagerServerConnection { #[async_trait] impl ServerHandler for ManagerServer { + type LocalData = DistantManagerServerConnection; type Request = ManagerRequest; type Response = ManagerResponse; - type LocalData = DistantManagerServerConnection; async fn on_request(&self, ctx: ServerCtx) { let ServerCtx { @@ -315,12 +318,13 @@ impl ServerHandler for ManagerServer { #[cfg(test)] mod tests { + use tokio::sync::mpsc; + use super::*; use crate::client::UntypedClient; use crate::common::FramedTransport; use crate::server::ServerReply; use crate::{boxed_connect_handler, boxed_launch_handler}; - use tokio::sync::mpsc; fn test_config() -> Config { Config { diff --git a/distant-net/src/manager/server/authentication.rs b/distant-net/src/manager/server/authentication.rs index 5c035d4..135c31b 100644 --- a/distant-net/src/manager/server/authentication.rs +++ b/distant-net/src/manager/server/authentication.rs @@ -1,12 +1,15 @@ -use crate::{ - common::authentication::{msg::*, Authenticator}, - manager::data::{ManagerAuthenticationId, ManagerResponse}, - server::ServerReply, -}; +use std::collections::HashMap; +use std::io; +use std::sync::Arc; + use async_trait::async_trait; -use std::{collections::HashMap, io, sync::Arc}; use tokio::sync::{oneshot, RwLock}; +use crate::common::authentication::msg::*; +use crate::common::authentication::Authenticator; +use crate::manager::data::{ManagerAuthenticationId, ManagerResponse}; +use crate::server::ServerReply; + /// Implementation of [`Authenticator`] used by a manger to perform authentication with /// remote servers it is managing. #[derive(Clone)] diff --git a/distant-net/src/manager/server/config.rs b/distant-net/src/manager/server/config.rs index d7d898a..38f3a91 100644 --- a/distant-net/src/manager/server/config.rs +++ b/distant-net/src/manager/server/config.rs @@ -1,6 +1,7 @@ -use super::{BoxedConnectHandler, BoxedLaunchHandler}; use std::collections::HashMap; +use super::{BoxedConnectHandler, BoxedLaunchHandler}; + /// Configuration settings for a manager. pub struct Config { /// Scheme to use when none is provided in a destination for launch diff --git a/distant-net/src/manager/server/connection.rs b/distant-net/src/manager/server/connection.rs index 7a673be..800bf1d 100644 --- a/distant-net/src/manager/server/connection.rs +++ b/distant-net/src/manager/server/connection.rs @@ -1,12 +1,14 @@ -use crate::{ - client::{Mailbox, UntypedClient}, - common::{ConnectionId, Destination, Map, UntypedRequest, UntypedResponse}, - manager::data::{ManagerChannelId, ManagerResponse}, - server::ServerReply, -}; +use std::collections::HashMap; +use std::io; + use log::*; -use std::{collections::HashMap, io}; -use tokio::{sync::mpsc, task::JoinHandle}; +use tokio::sync::mpsc; +use tokio::task::JoinHandle; + +use crate::client::{Mailbox, UntypedClient}; +use crate::common::{ConnectionId, Destination, Map, UntypedRequest, UntypedResponse}; +use crate::manager::data::{ManagerChannelId, ManagerResponse}; +use crate::server::ServerReply; /// Represents a connection a distant manager has with some distant-compatible server pub struct ManagerConnection { diff --git a/distant-net/src/manager/server/handler.rs b/distant-net/src/manager/server/handler.rs index ae7eacd..4a76a1d 100644 --- a/distant-net/src/manager/server/handler.rs +++ b/distant-net/src/manager/server/handler.rs @@ -1,7 +1,11 @@ -use crate::client::UntypedClient; -use crate::common::{authentication::Authenticator, Destination, Map}; +use std::future::Future; +use std::io; + use async_trait::async_trait; -use std::{future::Future, io}; + +use crate::client::UntypedClient; +use crate::common::authentication::Authenticator; +use crate::common::{Destination, Map}; pub type BoxedLaunchHandler = Box; pub type BoxedConnectHandler = Box; @@ -157,9 +161,10 @@ macro_rules! boxed_connect_handler { #[cfg(test)] mod tests { + use test_log::test; + use super::*; use crate::common::FramedTransport; - use test_log::test; #[inline] fn test_destination() -> Destination { diff --git a/distant-net/src/server.rs b/distant-net/src/server.rs index 4b1fbfd..c2a6ed4 100644 --- a/distant-net/src/server.rs +++ b/distant-net/src/server.rs @@ -1,10 +1,16 @@ -use crate::common::{authentication::Verifier, Listener, Response, Transport}; +use std::io; +use std::sync::Arc; +use std::time::Duration; + use async_trait::async_trait; use log::*; -use serde::{de::DeserializeOwned, Serialize}; -use std::{io, sync::Arc, time::Duration}; +use serde::de::DeserializeOwned; +use serde::Serialize; use tokio::sync::{broadcast, RwLock}; +use crate::common::authentication::Verifier; +use crate::common::{Listener, Response, Transport}; + mod builder; pub use builder::*; @@ -237,23 +243,25 @@ where #[cfg(test)] mod tests { - use super::*; - use crate::common::{ - authentication::{AuthenticationMethod, DummyAuthHandler, NoneAuthenticationMethod}, - Connection, InmemoryTransport, MpscListener, Request, Response, - }; - use async_trait::async_trait; use std::time::Duration; + + use async_trait::async_trait; use test_log::test; use tokio::sync::mpsc; + use super::*; + use crate::common::authentication::{ + AuthenticationMethod, DummyAuthHandler, NoneAuthenticationMethod, + }; + use crate::common::{Connection, InmemoryTransport, MpscListener, Request, Response}; + pub struct TestServerHandler; #[async_trait] impl ServerHandler for TestServerHandler { + type LocalData = (); type Request = u16; type Response = String; - type LocalData = (); async fn on_accept(&self, _: ConnectionCtx<'_, Self::LocalData>) -> io::Result<()> { Ok(()) diff --git a/distant-net/src/server/builder.rs b/distant-net/src/server/builder.rs index a732474..ac02fcc 100644 --- a/distant-net/src/server/builder.rs +++ b/distant-net/src/server/builder.rs @@ -7,9 +7,7 @@ mod unix; mod windows; pub use tcp::*; - #[cfg(unix)] pub use unix::*; - #[cfg(windows)] pub use windows::*; diff --git a/distant-net/src/server/builder/tcp.rs b/distant-net/src/server/builder/tcp.rs index 5feb2ce..7a94420 100644 --- a/distant-net/src/server/builder/tcp.rs +++ b/distant-net/src/server/builder/tcp.rs @@ -1,7 +1,12 @@ -use crate::common::{authentication::Verifier, PortRange, TcpListener}; +use std::io; +use std::net::IpAddr; + +use serde::de::DeserializeOwned; +use serde::Serialize; + +use crate::common::authentication::Verifier; +use crate::common::{PortRange, TcpListener}; use crate::server::{Server, ServerConfig, ServerHandler, TcpServerRef}; -use serde::{de::DeserializeOwned, Serialize}; -use std::{io, net::IpAddr}; pub struct TcpServerBuilder(Server); @@ -52,21 +57,24 @@ where #[cfg(test)] mod tests { + use std::net::{Ipv6Addr, SocketAddr}; + + use async_trait::async_trait; + use test_log::test; + use super::*; use crate::client::Client; - use crate::common::{authentication::DummyAuthHandler, Request}; + use crate::common::authentication::DummyAuthHandler; + use crate::common::Request; use crate::server::ServerCtx; - use async_trait::async_trait; - use std::net::{Ipv6Addr, SocketAddr}; - use test_log::test; pub struct TestServerHandler; #[async_trait] impl ServerHandler for TestServerHandler { + type LocalData = (); type Request = String; type Response = String; - type LocalData = (); async fn on_request(&self, ctx: ServerCtx) { // Echo back what we received diff --git a/distant-net/src/server/builder/unix.rs b/distant-net/src/server/builder/unix.rs index 94fd95e..a934544 100644 --- a/distant-net/src/server/builder/unix.rs +++ b/distant-net/src/server/builder/unix.rs @@ -1,7 +1,12 @@ -use crate::common::{authentication::Verifier, UnixSocketListener}; +use std::io; +use std::path::Path; + +use serde::de::DeserializeOwned; +use serde::Serialize; + +use crate::common::authentication::Verifier; +use crate::common::UnixSocketListener; use crate::server::{Server, ServerConfig, ServerHandler, UnixSocketServerRef}; -use serde::{de::DeserializeOwned, Serialize}; -use std::{io, path::Path}; pub struct UnixSocketServerBuilder(Server); @@ -53,21 +58,23 @@ where #[cfg(test)] mod tests { - use super::*; - use crate::client::Client; - use crate::common::{authentication::DummyAuthHandler, Request}; - use crate::server::ServerCtx; use async_trait::async_trait; use tempfile::NamedTempFile; use test_log::test; + use super::*; + use crate::client::Client; + use crate::common::authentication::DummyAuthHandler; + use crate::common::Request; + use crate::server::ServerCtx; + pub struct TestServerHandler; #[async_trait] impl ServerHandler for TestServerHandler { + type LocalData = (); type Request = String; type Response = String; - type LocalData = (); async fn on_request(&self, ctx: ServerCtx) { // Echo back what we received diff --git a/distant-net/src/server/builder/windows.rs b/distant-net/src/server/builder/windows.rs index 96e603a..9c5d272 100644 --- a/distant-net/src/server/builder/windows.rs +++ b/distant-net/src/server/builder/windows.rs @@ -1,10 +1,12 @@ -use crate::common::{authentication::Verifier, WindowsPipeListener}; +use std::ffi::{OsStr, OsString}; +use std::io; + +use serde::de::DeserializeOwned; +use serde::Serialize; + +use crate::common::authentication::Verifier; +use crate::common::WindowsPipeListener; use crate::server::{Server, ServerConfig, ServerHandler, WindowsPipeServerRef}; -use serde::{de::DeserializeOwned, Serialize}; -use std::{ - ffi::{OsStr, OsString}, - io, -}; pub struct WindowsPipeServerBuilder(Server); @@ -68,20 +70,22 @@ where #[cfg(test)] mod tests { + use async_trait::async_trait; + use test_log::test; + use super::*; use crate::client::Client; - use crate::common::{authentication::DummyAuthHandler, Request}; + use crate::common::authentication::DummyAuthHandler; + use crate::common::Request; use crate::server::ServerCtx; - use async_trait::async_trait; - use test_log::test; pub struct TestServerHandler; #[async_trait] impl ServerHandler for TestServerHandler { + type LocalData = (); type Request = String; type Response = String; - type LocalData = (); async fn on_request(&self, ctx: ServerCtx) { // Echo back what we received diff --git a/distant-net/src/server/config.rs b/distant-net/src/server/config.rs index 2fac22b..ed05ba9 100644 --- a/distant-net/src/server/config.rs +++ b/distant-net/src/server/config.rs @@ -1,6 +1,9 @@ +use std::num::ParseFloatError; +use std::str::FromStr; +use std::time::Duration; + use derive_more::{Display, Error}; use serde::{Deserialize, Serialize}; -use std::{num::ParseFloatError, str::FromStr, time::Duration}; const DEFAULT_CONNECTION_SLEEP: Duration = Duration::from_millis(1); const DEFAULT_HEARTBEAT_DURATION: Duration = Duration::from_secs(5); diff --git a/distant-net/src/server/connection.rs b/distant-net/src/server/connection.rs index c525267..1f63519 100644 --- a/distant-net/src/server/connection.rs +++ b/distant-net/src/server/connection.rs @@ -1,25 +1,22 @@ +use std::future::Future; +use std::io; +use std::pin::Pin; +use std::sync::{Arc, Weak}; +use std::task::{Context, Poll}; +use std::time::{Duration, Instant}; + +use log::*; +use serde::de::DeserializeOwned; +use serde::Serialize; +use tokio::sync::{broadcast, mpsc, oneshot, RwLock}; +use tokio::task::JoinHandle; + use super::{ ConnectionCtx, ConnectionState, ServerCtx, ServerHandler, ServerReply, ServerState, ShutdownTimer, }; -use crate::common::{ - authentication::{Keychain, Verifier}, - Backup, Connection, Frame, Interest, Response, Transport, UntypedRequest, -}; -use log::*; -use serde::{de::DeserializeOwned, Serialize}; -use std::{ - future::Future, - io, - pin::Pin, - sync::{Arc, Weak}, - task::{Context, Poll}, - time::{Duration, Instant}, -}; -use tokio::{ - sync::{broadcast, mpsc, oneshot, RwLock}, - task::JoinHandle, -}; +use crate::common::authentication::{Keychain, Verifier}; +use crate::common::{Backup, Connection, Frame, Interest, Response, Transport, UntypedRequest}; pub type ServerKeychain = Keychain>; @@ -591,23 +588,25 @@ where #[cfg(test)] mod tests { + use std::sync::atomic::{AtomicBool, Ordering}; + + use async_trait::async_trait; + use test_log::test; + use super::*; use crate::common::authentication::DummyAuthHandler; use crate::common::{ HeapSecretKey, InmemoryTransport, Ready, Reconnectable, Request, Response, }; use crate::server::Shutdown; - use async_trait::async_trait; - use std::sync::atomic::{AtomicBool, Ordering}; - use test_log::test; struct TestServerHandler; #[async_trait] impl ServerHandler for TestServerHandler { + type LocalData = (); type Request = u16; type Response = String; - type LocalData = (); async fn on_accept(&self, _: ConnectionCtx<'_, Self::LocalData>) -> io::Result<()> { Ok(()) @@ -734,9 +733,9 @@ mod tests { #[async_trait] impl ServerHandler for BadAcceptServerHandler { + type LocalData = (); type Request = u16; type Response = String; - type LocalData = (); async fn on_accept(&self, _: ConnectionCtx<'_, Self::LocalData>) -> io::Result<()> { Err(io::Error::new(io::ErrorKind::Other, "bad accept")) @@ -1026,9 +1025,9 @@ mod tests { #[async_trait] impl ServerHandler for HangingAcceptServerHandler { + type LocalData = (); type Request = (); type Response = (); - type LocalData = (); async fn on_accept(&self, _: ConnectionCtx<'_, Self::LocalData>) -> io::Result<()> { // Wait "forever" so we can ensure that we fail at this step @@ -1082,9 +1081,9 @@ mod tests { #[async_trait] impl ServerHandler for AcceptServerHandler { + type LocalData = (); type Request = (); type Response = (); - type LocalData = (); async fn on_accept(&self, _: ConnectionCtx<'_, Self::LocalData>) -> io::Result<()> { self.tx.send(()).await.unwrap(); diff --git a/distant-net/src/server/context.rs b/distant-net/src/server/context.rs index d1ecef6..7770b60 100644 --- a/distant-net/src/server/context.rs +++ b/distant-net/src/server/context.rs @@ -1,6 +1,7 @@ +use std::sync::Arc; + use super::ServerReply; use crate::common::{ConnectionId, Request}; -use std::sync::Arc; /// Represents contextual information for working with an inbound request pub struct ServerCtx { diff --git a/distant-net/src/server/ref.rs b/distant-net/src/server/ref.rs index f8f0fc5..28fe704 100644 --- a/distant-net/src/server/ref.rs +++ b/distant-net/src/server/ref.rs @@ -1,14 +1,14 @@ -use crate::common::AsAny; -use std::{ - future::Future, - io, - pin::Pin, - task::{Context, Poll}, - time::Duration, -}; +use std::future::Future; +use std::io; +use std::pin::Pin; +use std::task::{Context, Poll}; +use std::time::Duration; + use tokio::sync::broadcast; use tokio::task::{JoinError, JoinHandle}; +use crate::common::AsAny; + /// Interface to engage with a server instance. pub trait ServerRef: AsAny + Send { /// Returns true if the server is no longer running. diff --git a/distant-net/src/server/ref/tcp.rs b/distant-net/src/server/ref/tcp.rs index c6bc81f..f0ee233 100644 --- a/distant-net/src/server/ref/tcp.rs +++ b/distant-net/src/server/ref/tcp.rs @@ -1,6 +1,7 @@ -use super::ServerRef; use std::net::IpAddr; +use super::ServerRef; + /// Reference to a TCP server instance pub struct TcpServerRef { pub(crate) addr: IpAddr, diff --git a/distant-net/src/server/ref/unix.rs b/distant-net/src/server/ref/unix.rs index 120ff31..50bdb0f 100644 --- a/distant-net/src/server/ref/unix.rs +++ b/distant-net/src/server/ref/unix.rs @@ -1,6 +1,7 @@ -use super::ServerRef; use std::path::{Path, PathBuf}; +use super::ServerRef; + /// Reference to a unix socket server instance pub struct UnixSocketServerRef { pub(crate) path: PathBuf, diff --git a/distant-net/src/server/ref/windows.rs b/distant-net/src/server/ref/windows.rs index df59ced..bf768e1 100644 --- a/distant-net/src/server/ref/windows.rs +++ b/distant-net/src/server/ref/windows.rs @@ -1,6 +1,7 @@ -use super::ServerRef; use std::ffi::{OsStr, OsString}; +use super::ServerRef; + /// Reference to a unix socket server instance pub struct WindowsPipeServerRef { pub(crate) addr: OsString, diff --git a/distant-net/src/server/reply.rs b/distant-net/src/server/reply.rs index eaa422f..0eca1ec 100644 --- a/distant-net/src/server/reply.rs +++ b/distant-net/src/server/reply.rs @@ -1,7 +1,12 @@ -use crate::common::{Id, Response}; -use std::{future::Future, io, pin::Pin, sync::Arc}; +use std::future::Future; +use std::io; +use std::pin::Pin; +use std::sync::Arc; + use tokio::sync::{mpsc, Mutex}; +use crate::common::{Id, Response}; + /// Interface to send a reply to some request pub trait Reply: Send + Sync { type Data; diff --git a/distant-net/src/server/shutdown_timer.rs b/distant-net/src/server/shutdown_timer.rs index fc83639..09830f4 100644 --- a/distant-net/src/server/shutdown_timer.rs +++ b/distant-net/src/server/shutdown_timer.rs @@ -1,9 +1,11 @@ -use super::Shutdown; -use crate::common::utils::Timer; -use log::*; use std::time::Duration; + +use log::*; use tokio::sync::watch; +use super::Shutdown; +use crate::common::utils::Timer; + /// Cloneable notification for when a [`ShutdownTimer`] has completed. #[derive(Clone)] pub(crate) struct ShutdownNotification(watch::Receiver<()>); diff --git a/distant-net/src/server/state.rs b/distant-net/src/server/state.rs index cba27be..c937f6c 100644 --- a/distant-net/src/server/state.rs +++ b/distant-net/src/server/state.rs @@ -1,8 +1,11 @@ -use crate::common::{authentication::Keychain, Backup, ConnectionId}; use std::collections::HashMap; + use tokio::sync::{mpsc, oneshot, RwLock}; use tokio::task::JoinHandle; +use crate::common::authentication::Keychain; +use crate::common::{Backup, ConnectionId}; + /// Contains all top-level state for the server pub struct ServerState { /// Mapping of connection ids to their tasks. diff --git a/distant-net/tests/manager_tests.rs b/distant-net/tests/manager_tests.rs index 783f68b..e32b180 100644 --- a/distant-net/tests/manager_tests.rs +++ b/distant-net/tests/manager_tests.rs @@ -1,3 +1,5 @@ +use std::io; + use async_trait::async_trait; use distant_net::boxed_connect_handler; use distant_net::client::Client; @@ -6,16 +8,15 @@ use distant_net::common::{Destination, InmemoryTransport, Map, OneshotListener}; use distant_net::manager::{Config, ManagerClient, ManagerServer}; use distant_net::server::{Server, ServerCtx, ServerHandler}; use log::*; -use std::io; use test_log::test; struct TestServerHandler; #[async_trait] impl ServerHandler for TestServerHandler { + type LocalData = (); type Request = String; type Response = String; - type LocalData = (); async fn on_request(&self, ctx: ServerCtx) { ctx.reply diff --git a/distant-net/tests/typed_tests.rs b/distant-net/tests/typed_tests.rs index 1bb9eaa..650b936 100644 --- a/distant-net/tests/typed_tests.rs +++ b/distant-net/tests/typed_tests.rs @@ -10,9 +10,9 @@ struct TestServerHandler; #[async_trait] impl ServerHandler for TestServerHandler { + type LocalData = (); type Request = (u8, String); type Response = String; - type LocalData = (); async fn on_request(&self, ctx: ServerCtx) { let (cnt, msg) = ctx.request.payload; diff --git a/distant-net/tests/untyped_tests.rs b/distant-net/tests/untyped_tests.rs index 12b775d..be5cb47 100644 --- a/distant-net/tests/untyped_tests.rs +++ b/distant-net/tests/untyped_tests.rs @@ -10,9 +10,9 @@ struct TestServerHandler; #[async_trait] impl ServerHandler for TestServerHandler { + type LocalData = (); type Request = (u8, String); type Response = String; - type LocalData = (); async fn on_request(&self, ctx: ServerCtx) { let (cnt, msg) = ctx.request.payload; diff --git a/distant-ssh2/src/api.rs b/distant-ssh2/src/api.rs index fb73c1a..f31062c 100644 --- a/distant-ssh2/src/api.rs +++ b/distant-ssh2/src/api.rs @@ -1,29 +1,25 @@ -use crate::{ - process::{spawn_pty, spawn_simple, SpawnResult}, - utils::{self, to_other_error}, -}; +use std::collections::{HashMap, HashSet}; +use std::io; +use std::path::PathBuf; +use std::sync::{Arc, Weak}; +use std::time::Duration; + use async_compat::CompatExt; use async_once_cell::OnceCell; use async_trait::async_trait; -use distant_core::{ - data::{ - Capabilities, CapabilityKind, DirEntry, Environment, FileType, Metadata, ProcessId, - PtySize, SystemInfo, UnixMetadata, - }, - net::server::ConnectionCtx, - DistantApi, DistantCtx, +use distant_core::data::{ + Capabilities, CapabilityKind, DirEntry, Environment, FileType, Metadata, ProcessId, PtySize, + SystemInfo, UnixMetadata, }; +use distant_core::net::server::ConnectionCtx; +use distant_core::{DistantApi, DistantCtx}; use log::*; -use std::{ - collections::{HashMap, HashSet}, - io, - path::PathBuf, - sync::{Arc, Weak}, - time::Duration, -}; use tokio::sync::{mpsc, RwLock}; use wezterm_ssh::{FilePermissions, OpenFileType, OpenOptions, Session as WezSession, WriteMode}; +use crate::process::{spawn_pty, spawn_simple, SpawnResult}; +use crate::utils::{self, to_other_error}; + /// Time after copy completes to wait for stdout/stderr to close const COPY_COMPLETE_TIMEOUT: Duration = Duration::from_secs(1); diff --git a/distant-ssh2/src/lib.rs b/distant-ssh2/src/lib.rs index 708d9cd..0e4b006 100644 --- a/distant-ssh2/src/lib.rs +++ b/distant-ssh2/src/lib.rs @@ -1,29 +1,24 @@ #[cfg(not(any(feature = "libssh", feature = "ssh2")))] compile_error!("Either feature \"libssh\" or \"ssh2\" must be enabled for this crate."); +use std::collections::BTreeMap; +use std::fmt; +use std::io::{self, Write}; +use std::net::{IpAddr, SocketAddr}; +use std::path::PathBuf; +use std::str::FromStr; +use std::time::Duration; + use async_compat::CompatExt; use async_once_cell::OnceCell; use async_trait::async_trait; -use distant_core::{ - net::{ - client::{Client, ClientConfig}, - common::authentication::{AuthHandlerMap, DummyAuthHandler, Verifier}, - common::{Host, InmemoryTransport, OneshotListener}, - server::{Server, ServerRef}, - }, - DistantApiServerHandler, DistantClient, DistantSingleKeyCredentials, -}; +use distant_core::net::client::{Client, ClientConfig}; +use distant_core::net::common::authentication::{AuthHandlerMap, DummyAuthHandler, Verifier}; +use distant_core::net::common::{Host, InmemoryTransport, OneshotListener}; +use distant_core::net::server::{Server, ServerRef}; +use distant_core::{DistantApiServerHandler, DistantClient, DistantSingleKeyCredentials}; use log::*; use smol::channel::Receiver as SmolReceiver; -use std::{ - collections::BTreeMap, - fmt, - io::{self, Write}, - net::{IpAddr, SocketAddr}, - path::PathBuf, - str::FromStr, - time::Duration, -}; use wezterm_ssh::{ ChildKiller, Config as WezConfig, MasterPty, PtySize, Session as WezSession, SessionEvent as WezSessionEvent, diff --git a/distant-ssh2/src/process.rs b/distant-ssh2/src/process.rs index 07b182d..f7c119d 100644 --- a/distant-ssh2/src/process.rs +++ b/distant-ssh2/src/process.rs @@ -1,16 +1,14 @@ +use std::future::Future; +use std::io::{self, Read, Write}; +use std::path::PathBuf; +use std::time::Duration; + use async_compat::CompatExt; -use distant_core::{ - data::{DistantResponseData, Environment, ProcessId, PtySize}, - net::server::Reply, -}; +use distant_core::data::{DistantResponseData, Environment, ProcessId, PtySize}; +use distant_core::net::server::Reply; use log::*; -use std::{ - future::Future, - io::{self, Read, Write}, - path::PathBuf, - time::Duration, -}; -use tokio::{sync::mpsc, task::JoinHandle}; +use tokio::sync::mpsc; +use tokio::task::JoinHandle; use wezterm_ssh::{ Child, ChildKiller, ExecResult, MasterPty, PtySize as PortablePtySize, Session, SshChildProcess, }; diff --git a/distant-ssh2/src/utils.rs b/distant-ssh2/src/utils.rs index c89dfd5..b9fb782 100644 --- a/distant-ssh2/src/utils.rs +++ b/distant-ssh2/src/utils.rs @@ -1,10 +1,10 @@ +use std::path::{Path, PathBuf}; +use std::time::Duration; +use std::{fmt, io}; + use async_compat::CompatExt; -use std::{ - fmt, io, - path::{Path, PathBuf}, - time::Duration, -}; -use typed_path::{windows::WindowsComponent, Components, WindowsPath, WindowsPathBuf}; +use typed_path::windows::WindowsComponent; +use typed_path::{Components, WindowsPath, WindowsPathBuf}; use wezterm_ssh::{ExecResult, Session, Sftp}; const SSH_EXEC_TIMEOUT: Option = Some(Duration::from_secs(1)); diff --git a/distant-ssh2/tests/ssh2/client.rs b/distant-ssh2/tests/ssh2/client.rs index 338ad79..560f133 100644 --- a/distant-ssh2/tests/ssh2/client.rs +++ b/distant-ssh2/tests/ssh2/client.rs @@ -1,15 +1,18 @@ -use crate::sshd::*; -use assert_fs::{prelude::*, TempDir}; -use distant_core::{ - data::{ChangeKindSet, Environment, FileType, Metadata}, - DistantChannelExt, DistantClient, -}; +use std::io; +use std::path::Path; +use std::time::Duration; + +use assert_fs::prelude::*; +use assert_fs::TempDir; +use distant_core::data::{ChangeKindSet, Environment, FileType, Metadata}; +use distant_core::{DistantChannelExt, DistantClient}; use once_cell::sync::Lazy; use predicates::prelude::*; use rstest::*; -use std::{io, path::Path, time::Duration}; use test_log::test; +use crate::sshd::*; + const SETUP_DIR_TIMEOUT: Duration = Duration::from_secs(1); const SETUP_DIR_POLL: Duration = Duration::from_millis(50); diff --git a/distant-ssh2/tests/ssh2/launched.rs b/distant-ssh2/tests/ssh2/launched.rs index 4e0206f..5d5ac82 100644 --- a/distant-ssh2/tests/ssh2/launched.rs +++ b/distant-ssh2/tests/ssh2/launched.rs @@ -1,15 +1,17 @@ -use crate::sshd::*; -use assert_fs::{prelude::*, TempDir}; -use distant_core::{ - data::{ChangeKindSet, Environment, FileType, Metadata}, - DistantChannelExt, DistantClient, -}; +use std::path::Path; +use std::time::Duration; + +use assert_fs::prelude::*; +use assert_fs::TempDir; +use distant_core::data::{ChangeKindSet, Environment, FileType, Metadata}; +use distant_core::{DistantChannelExt, DistantClient}; use once_cell::sync::Lazy; use predicates::prelude::*; use rstest::*; -use std::{path::Path, time::Duration}; use test_log::test; +use crate::sshd::*; + static TEMP_SCRIPT_DIR: Lazy = Lazy::new(|| TempDir::new().unwrap()); static SCRIPT_RUNNER: Lazy = Lazy::new(|| String::from("bash")); diff --git a/distant-ssh2/tests/ssh2/ssh.rs b/distant-ssh2/tests/ssh2/ssh.rs index 2990f50..62006a6 100644 --- a/distant-ssh2/tests/ssh2/ssh.rs +++ b/distant-ssh2/tests/ssh2/ssh.rs @@ -1,8 +1,9 @@ -use crate::sshd::*; use distant_ssh2::{Ssh, SshFamily}; use rstest::*; use test_log::test; +use crate::sshd::*; + #[rstest] #[test(tokio::test)] async fn detect_family_should_return_windows_if_sshd_on_windows(#[future] ssh: Ctx) { diff --git a/distant-ssh2/tests/sshd/mod.rs b/distant-ssh2/tests/sshd/mod.rs index 09a49a0..096de64 100644 --- a/distant-ssh2/tests/sshd/mod.rs +++ b/distant-ssh2/tests/sshd/mod.rs @@ -1,30 +1,26 @@ -use crate::utils::ci_path_to_string; +use std::collections::HashMap; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; +#[cfg(unix)] +use std::os::unix::fs::PermissionsExt; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command}; +use std::sync::atomic::{AtomicU16, Ordering}; +use std::sync::Mutex; +use std::time::{Duration, Instant}; +use std::{fmt, io, thread}; + use anyhow::Context; -use assert_fs::{prelude::*, TempDir}; +use assert_fs::prelude::*; +use assert_fs::TempDir; use async_trait::async_trait; -use derive_more::Display; -use derive_more::{Deref, DerefMut}; +use derive_more::{Deref, DerefMut, Display}; use distant_core::DistantClient; use distant_ssh2::{DistantLaunchOpts, Ssh, SshAuthEvent, SshAuthHandler, SshOpts}; use log::*; use once_cell::sync::Lazy; use rstest::*; -use std::{ - collections::HashMap, - fmt, io, - net::{IpAddr, Ipv4Addr, Ipv6Addr}, - path::{Path, PathBuf}, - process::{Child, Command}, - sync::{ - atomic::{AtomicU16, Ordering}, - Mutex, - }, - thread, - time::{Duration, Instant}, -}; -#[cfg(unix)] -use std::os::unix::fs::PermissionsExt; +use crate::utils::ci_path_to_string; #[derive(Deref, DerefMut)] pub struct Ctx { diff --git a/distant-ssh2/tests/utils/mod.rs b/distant-ssh2/tests/utils/mod.rs index 24515a3..10cfc82 100644 --- a/distant-ssh2/tests/utils/mod.rs +++ b/distant-ssh2/tests/utils/mod.rs @@ -1,6 +1,7 @@ -use once_cell::sync::Lazy; use std::path::{Component, Path, Prefix}; +use once_cell::sync::Lazy; + // Returns true if running test in Github CI pub static IS_CI: Lazy = Lazy::new(|| std::env::var("CI").as_deref() == Ok("true")); diff --git a/rustfmt.toml b/rustfmt.toml index 2b493f7..e14f7e7 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -4,8 +4,8 @@ indent_style = "Block" use_field_init_shorthand = true # Unstable features -# unstable_features = true -# imports_granularity = "Crate" -# group_imports = "StdExternalCrate" -# reorder_impl_items = true -# normalize_doc_attributes = true +unstable_features = true +imports_granularity = "Module" +group_imports = "StdExternalCrate" +reorder_impl_items = true +normalize_doc_attributes = true diff --git a/src/cli.rs b/src/cli.rs index 683f904..05e6774 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -1,16 +1,14 @@ +use std::ffi::OsString; + use crate::options::DistantSubcommand; use crate::{CliResult, Options}; -use std::ffi::OsString; mod commands; mod common; -pub(crate) use common::Cache; -pub(crate) use common::Client; -pub(crate) use common::Manager; - #[cfg_attr(unix, allow(unused_imports))] pub(crate) use common::Spawner; +pub(crate) use common::{Cache, Client, Manager}; /// Represents the primary CLI entrypoint #[derive(Debug)] diff --git a/src/cli/commands/client.rs b/src/cli/commands/client.rs index cf6226a..a174d12 100644 --- a/src/cli/commands/client.rs +++ b/src/cli/commands/client.rs @@ -1,29 +1,38 @@ -use crate::cli::common::{ - Cache, Client, JsonAuthHandler, MsgReceiver, MsgSender, PromptAuthHandler, -}; -use crate::constants::MAX_PIPE_CHUNK_SIZE; -use crate::options::{ClientFileSystemSubcommand, ClientSubcommand, Format, NetworkSettings}; -use crate::{CliError, CliResult}; +use std::io; +use std::io::Write; +use std::path::Path; +use std::time::Duration; + use anyhow::Context; use distant_core::data::{ChangeKindSet, FileType, SearchQuery, SystemInfo}; use distant_core::net::common::{ConnectionId, Host, Map, Request, Response}; use distant_core::net::manager::ManagerClient; -use distant_core::{DistantChannel, DistantChannelExt, Watcher}; -use distant_core::{DistantMsg, DistantRequestData, DistantResponseData, RemoteCommand, Searcher}; +use distant_core::{ + DistantChannel, DistantChannelExt, DistantMsg, DistantRequestData, DistantResponseData, + RemoteCommand, Searcher, Watcher, +}; use log::*; use serde_json::json; -use std::io::Write; -use std::{io, path::Path, time::Duration}; -use tabled::{object::Rows, style::Style, Alignment, Disable, Modify, Table, Tabled}; +use tabled::object::Rows; +use tabled::style::Style; +use tabled::{Alignment, Disable, Modify, Table, Tabled}; use tokio::sync::mpsc; +use crate::cli::common::{ + Cache, Client, JsonAuthHandler, MsgReceiver, MsgSender, PromptAuthHandler, +}; +use crate::constants::MAX_PIPE_CHUNK_SIZE; +use crate::options::{ClientFileSystemSubcommand, ClientSubcommand, Format, NetworkSettings}; +use crate::{CliError, CliResult}; + mod lsp; mod shell; -use super::common::{Formatter, RemoteProcessLink}; use lsp::Lsp; use shell::Shell; +use super::common::{Formatter, RemoteProcessLink}; + const SLEEP_DURATION: Duration = Duration::from_millis(1); pub fn run(cmd: ClientSubcommand) -> CliResult { diff --git a/src/cli/commands/client/lsp.rs b/src/cli/commands/client/lsp.rs index abb4153..b1f982a 100644 --- a/src/cli/commands/client/lsp.rs +++ b/src/cli/commands/client/lsp.rs @@ -1,10 +1,13 @@ -use super::super::common::RemoteProcessLink; -use super::{CliError, CliResult}; -use anyhow::Context; -use distant_core::{data::PtySize, DistantChannel, RemoteLspCommand}; use std::path::PathBuf; + +use anyhow::Context; +use distant_core::data::PtySize; +use distant_core::{DistantChannel, RemoteLspCommand}; use terminal_size::{terminal_size, Height, Width}; +use super::super::common::RemoteProcessLink; +use super::{CliError, CliResult}; + #[derive(Clone)] pub struct Lsp(DistantChannel); diff --git a/src/cli/commands/client/shell.rs b/src/cli/commands/client/shell.rs index d3ff492..2018668 100644 --- a/src/cli/commands/client/shell.rs +++ b/src/cli/commands/client/shell.rs @@ -1,19 +1,17 @@ -use super::super::common::RemoteProcessLink; -use super::{CliError, CliResult}; -use anyhow::Context; -use distant_core::{ - data::{Environment, PtySize}, - DistantChannel, DistantChannelExt, RemoteCommand, -}; -use log::*; use std::path::PathBuf; use std::time::Duration; + +use anyhow::Context; +use distant_core::data::{Environment, PtySize}; +use distant_core::{DistantChannel, DistantChannelExt, RemoteCommand}; +use log::*; use terminal_size::{terminal_size, Height, Width}; -use termwiz::{ - caps::Capabilities, - input::{InputEvent, KeyCodeEncodeModes, KeyboardEncoding}, - terminal::{new_terminal, Terminal}, -}; +use termwiz::caps::Capabilities; +use termwiz::input::{InputEvent, KeyCodeEncodeModes, KeyboardEncoding}; +use termwiz::terminal::{new_terminal, Terminal}; + +use super::super::common::RemoteProcessLink; +use super::{CliError, CliResult}; #[derive(Clone)] pub struct Shell(DistantChannel); diff --git a/src/cli/commands/common/format.rs b/src/cli/commands/common/format.rs index b630ad7..af3261a 100644 --- a/src/cli/commands/common/format.rs +++ b/src/cli/commands/common/format.rs @@ -1,18 +1,18 @@ -use crate::options::Format; -use distant_core::{ - data::{ - ChangeKind, DistantMsg, DistantResponseData, Error, FileType, Metadata, - SearchQueryContentsMatch, SearchQueryMatch, SearchQueryPathMatch, SystemInfo, - }, - net::common::Response, +use std::collections::HashMap; +use std::io::{self, Write}; +use std::path::PathBuf; + +use distant_core::data::{ + ChangeKind, DistantMsg, DistantResponseData, Error, FileType, Metadata, + SearchQueryContentsMatch, SearchQueryMatch, SearchQueryPathMatch, SystemInfo, }; +use distant_core::net::common::Response; use log::*; -use std::{ - collections::HashMap, - io::{self, Write}, - path::PathBuf, -}; -use tabled::{object::Rows, style::Style, Alignment, Disable, Modify, Table, Tabled}; +use tabled::object::Rows; +use tabled::style::Style; +use tabled::{Alignment, Disable, Modify, Table, Tabled}; + +use crate::options::Format; #[derive(Default)] struct FormatterState { diff --git a/src/cli/commands/common/link.rs b/src/cli/commands/common/link.rs index 2a0bd52..44583c4 100644 --- a/src/cli/commands/common/link.rs +++ b/src/cli/commands/common/link.rs @@ -1,14 +1,14 @@ -use super::stdin; +use std::io::{self, Write}; +use std::thread; + use distant_core::{ RemoteLspStderr, RemoteLspStdin, RemoteLspStdout, RemoteStderr, RemoteStdin, RemoteStdout, }; use log::*; -use std::{ - io::{self, Write}, - thread, -}; use tokio::task::{JoinError, JoinHandle}; +use super::stdin; + /// Represents a link between a remote process' stdin/stdout/stderr and this process' /// stdin/stdout/stderr pub struct RemoteProcessLink { diff --git a/src/cli/commands/common/stdin.rs b/src/cli/commands/common/stdin.rs index 0a84d46..80fffb2 100644 --- a/src/cli/commands/common/stdin.rs +++ b/src/cli/commands/common/stdin.rs @@ -1,8 +1,7 @@ +use std::io::{self, BufReader, Read}; +use std::thread; + use log::error; -use std::{ - io::{self, BufReader, Read}, - thread, -}; use tokio::sync::mpsc; /// Creates a new thread that performs stdin reads in a blocking fashion, returning diff --git a/src/cli/commands/generate.rs b/src/cli/commands/generate.rs index 147bec6..f16cd1f 100644 --- a/src/cli/commands/generate.rs +++ b/src/cli/commands/generate.rs @@ -1,11 +1,13 @@ -use crate::options::{Config, GenerateSubcommand}; -use crate::{CliResult, Options}; +use std::{fs, io}; + use anyhow::Context; use clap::CommandFactory; use clap_complete::generate as clap_generate; use distant_core::net::common::{Request, Response}; use distant_core::{DistantMsg, DistantRequestData, DistantResponseData}; -use std::{fs, io}; + +use crate::options::{Config, GenerateSubcommand}; +use crate::{CliResult, Options}; pub fn run(cmd: GenerateSubcommand) -> CliResult { let rt = tokio::runtime::Runtime::new().context("Failed to start up runtime")?; diff --git a/src/cli/commands/manager.rs b/src/cli/commands/manager.rs index 686cd14..e05620a 100644 --- a/src/cli/commands/manager.rs +++ b/src/cli/commands/manager.rs @@ -1,9 +1,11 @@ -use crate::cli::common::{MsgReceiver, MsgSender}; -use crate::cli::{Cache, Client, Manager}; -use crate::options::{Format, ManagerServiceSubcommand, ManagerSubcommand, NetworkSettings}; -use crate::{CliError, CliResult}; +use std::collections::HashMap; +use std::ffi::OsString; +use std::path::PathBuf; + use anyhow::Context; -use dialoguer::{console::Term, theme::ColorfulTheme, Select}; +use dialoguer::console::Term; +use dialoguer::theme::ColorfulTheme; +use dialoguer::Select; use distant_core::net::common::ConnectionId; use distant_core::net::manager::{ Config as NetManagerConfig, ConnectHandler, LaunchHandler, ManagerClient, @@ -15,9 +17,13 @@ use service_manager::{ ServiceInstallCtx, ServiceLabel, ServiceLevel, ServiceManager, ServiceStartCtx, ServiceStopCtx, ServiceUninstallCtx, }; -use std::{collections::HashMap, ffi::OsString, path::PathBuf}; use tabled::{Table, Tabled}; +use crate::cli::common::{MsgReceiver, MsgSender}; +use crate::cli::{Cache, Client, Manager}; +use crate::options::{Format, ManagerServiceSubcommand, ManagerSubcommand, NetworkSettings}; +use crate::{CliError, CliResult}; + /// [`ServiceLabel`] for our manager in the form `rocks.distant.manager` static SERVICE_LABEL: Lazy = Lazy::new(|| ServiceLabel { qualifier: String::from("rocks"), diff --git a/src/cli/commands/manager/handlers.rs b/src/cli/commands/manager/handlers.rs index b05bdd3..d425dfd 100644 --- a/src/cli/commands/manager/handlers.rs +++ b/src/cli/commands/manager/handlers.rs @@ -1,4 +1,9 @@ -use crate::options::{BindAddress, ClientLaunchConfig}; +use std::io; +use std::net::{IpAddr, SocketAddr}; +use std::path::PathBuf; +use std::process::Stdio; +use std::time::Duration; + use async_trait::async_trait; use distant_core::net::client::{Client, ClientConfig, ReconnectStrategy, UntypedClient}; use distant_core::net::common::authentication::msg::*; @@ -9,18 +14,11 @@ use distant_core::net::common::authentication::{ use distant_core::net::common::{Destination, Map, SecretKey32}; use distant_core::net::manager::{ConnectHandler, LaunchHandler}; use log::*; -use std::{ - io, - net::{IpAddr, SocketAddr}, - path::PathBuf, - process::Stdio, - time::Duration, -}; -use tokio::{ - io::{AsyncBufReadExt, BufReader}, - process::{Child, Command}, - sync::Mutex, -}; +use tokio::io::{AsyncBufReadExt, BufReader}; +use tokio::process::{Child, Command}; +use tokio::sync::Mutex; + +use crate::options::{BindAddress, ClientLaunchConfig}; #[inline] fn missing(label: &str) -> io::Error { diff --git a/src/cli/commands/server.rs b/src/cli/commands/server.rs index 113a667..aa41aaf 100644 --- a/src/cli/commands/server.rs +++ b/src/cli/commands/server.rs @@ -1,12 +1,14 @@ -use crate::options::ServerSubcommand; -use crate::{CliError, CliResult}; +use std::io::{self, Read, Write}; + use anyhow::Context; use distant_core::net::common::authentication::Verifier; use distant_core::net::common::{Host, SecretKey32}; use distant_core::net::server::{Server, ServerConfig as NetServerConfig, ServerRef}; use distant_core::{DistantApiServerHandler, DistantSingleKeyCredentials}; use log::*; -use std::io::{self, Read, Write}; + +use crate::options::ServerSubcommand; +use crate::{CliError, CliResult}; pub fn run(cmd: ServerSubcommand) -> CliResult { match &cmd { @@ -20,9 +22,11 @@ pub fn run(cmd: ServerSubcommand) -> CliResult { #[cfg(windows)] fn run_daemon(_cmd: ServerSubcommand) -> CliResult { - use crate::cli::Spawner; - use distant_core::net::common::{Listener, TransportExt, WindowsPipeListener}; use std::ffi::OsString; + + use distant_core::net::common::{Listener, TransportExt, WindowsPipeListener}; + + use crate::cli::Spawner; let rt = tokio::runtime::Runtime::new().context("Failed to start up runtime")?; rt.block_on(async { let name = format!("distant_{}_{}", std::process::id(), rand::random::()); diff --git a/src/cli/common/cache.rs b/src/cli/common/cache.rs index af45484..b80c3de 100644 --- a/src/cli/common/cache.rs +++ b/src/cli/common/cache.rs @@ -1,11 +1,11 @@ -use crate::constants::user::CACHE_FILE_PATH; +use std::io; +use std::path::{Path, PathBuf}; + use anyhow::Context; use distant_core::net::common::ConnectionId; use serde::{Deserialize, Serialize}; -use std::{ - io, - path::{Path, PathBuf}, -}; + +use crate::constants::user::CACHE_FILE_PATH; mod id; pub use id::CacheId; diff --git a/src/cli/common/cache/id.rs b/src/cli/common/cache/id.rs index b0a4d6f..563c12a 100644 --- a/src/cli/common/cache/id.rs +++ b/src/cli/common/cache/id.rs @@ -1,10 +1,9 @@ +use std::convert::TryFrom; +use std::fmt; +use std::ops::{Deref, DerefMut}; +use std::str::FromStr; + use serde::{Deserialize, Serialize}; -use std::{ - convert::TryFrom, - fmt, - ops::{Deref, DerefMut}, - str::FromStr, -}; /// NOTE: This type only exists due to a bug with toml-rs where a u64 cannot be stored if its /// value is greater than i64's max as it gets written as a negative number and then diff --git a/src/cli/common/client.rs b/src/cli/common/client.rs index 2439d53..b8af4e5 100644 --- a/src/cli/common/client.rs +++ b/src/cli/common/client.rs @@ -1,5 +1,6 @@ -use crate::cli::common::{MsgReceiver, MsgSender}; -use crate::options::NetworkSettings; +use std::io; +use std::time::Duration; + use async_trait::async_trait; use distant_core::net::client::{Client as NetClient, ClientConfig, ReconnectStrategy}; use distant_core::net::common::authentication::msg::*; @@ -8,8 +9,9 @@ use distant_core::net::common::authentication::{ }; use distant_core::net::manager::ManagerClient; use log::*; -use std::io; -use std::time::Duration; + +use crate::cli::common::{MsgReceiver, MsgSender}; +use crate::options::NetworkSettings; pub struct Client { network: NetworkSettings, diff --git a/src/cli/common/manager.rs b/src/cli/common/manager.rs index d11d138..4f9653d 100644 --- a/src/cli/common/manager.rs +++ b/src/cli/common/manager.rs @@ -1,13 +1,12 @@ -use crate::{ - constants::{global as global_paths, user as user_paths}, - options::{AccessControl, NetworkSettings}, -}; use anyhow::Context; use distant_core::net::common::authentication::Verifier; use distant_core::net::manager::{Config as ManagerConfig, ManagerServer}; use distant_core::net::server::ServerRef; use log::*; +use crate::constants::{global as global_paths, user as user_paths}; +use crate::options::{AccessControl, NetworkSettings}; + pub struct Manager { pub access: AccessControl, pub config: ManagerConfig, diff --git a/src/cli/common/msg.rs b/src/cli/common/msg.rs index bb3776f..910f82f 100644 --- a/src/cli/common/msg.rs +++ b/src/cli/common/msg.rs @@ -1,10 +1,10 @@ +use std::io::{self, Write}; +use std::sync::{Arc, Mutex}; +use std::thread; + use log::*; -use serde::{de::DeserializeOwned, Serialize}; -use std::{ - io::{self, Write}, - sync::{Arc, Mutex}, - thread, -}; +use serde::de::DeserializeOwned; +use serde::Serialize; use tokio::sync::mpsc; type SendFn = Arc io::Result<()> + Send>>>; diff --git a/src/cli/common/spawner.rs b/src/cli/common/spawner.rs index 5816746..70b8bb4 100644 --- a/src/cli/common/spawner.rs +++ b/src/cli/common/spawner.rs @@ -1,10 +1,9 @@ +use std::ffi::{OsStr, OsString}; +use std::path::PathBuf; +use std::process::{Command, Stdio}; + use anyhow::Context; use log::*; -use std::{ - ffi::{OsStr, OsString}, - path::PathBuf, - process::{Command, Stdio}, -}; /// Utility functions to spawn a process in the background #[allow(dead_code)] @@ -102,10 +101,8 @@ impl Spawner { /// Spawns a process on Windows that runs in the background without a console and does not get /// terminated when the parent or other ancestors terminate (such as openssh session) pub fn spawn_background(cmd: impl AsRef) -> anyhow::Result { - use std::{ - io::{BufRead, Cursor}, - os::windows::process::CommandExt, - }; + use std::io::{BufRead, Cursor}; + use std::os::windows::process::CommandExt; // Get absolute path to powershell let powershell = which::which("powershell.exe").context("Failed to find powershell.exe")?; diff --git a/src/constants.rs b/src/constants.rs index fd1508c..ac68cad 100644 --- a/src/constants.rs +++ b/src/constants.rs @@ -1,6 +1,7 @@ +use std::path::PathBuf; + use directories::ProjectDirs; use once_cell::sync::Lazy; -use std::path::PathBuf; /// Represents the maximum size (in bytes) that data will be read from pipes /// per individual `read` call diff --git a/src/lib.rs b/src/lib.rs index bbab03d..5f7ebdf 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,7 @@ -use derive_more::{Display, Error, From}; use std::process::{ExitCode, Termination}; +use derive_more::{Display, Error, From}; + mod cli; mod constants; mod options; diff --git a/src/options.rs b/src/options.rs index 95171fd..34158f4 100644 --- a/src/options.rs +++ b/src/options.rs @@ -1,5 +1,6 @@ -use crate::constants; -use crate::constants::user::CACHE_FILE_PATH_STR; +use std::ffi::OsString; +use std::path::{Path, PathBuf}; + use clap::builder::TypedValueParser as _; use clap::{Parser, Subcommand, ValueEnum, ValueHint}; use clap_complete::Shell as ClapCompleteShell; @@ -8,15 +9,17 @@ use distant_core::data::{ChangeKind, Environment}; use distant_core::net::common::{ConnectionId, Destination, Map, PortRange}; use distant_core::net::server::Shutdown; use service_manager::ServiceManagerKind; -use std::ffi::OsString; -use std::path::{Path, PathBuf}; + +use crate::constants; +use crate::constants::user::CACHE_FILE_PATH_STR; mod common; mod config; -pub use self::config::*; pub use common::*; +pub use self::config::*; + /// Primary entrypoint into options & subcommands for the CLI. #[derive(Debug, PartialEq, Parser)] #[clap(author, version, about)] @@ -1103,10 +1106,12 @@ impl Default for Format { #[cfg(test)] mod tests { - use super::*; + use std::time::Duration; + use distant_core::net::common::Host; use distant_core::net::map; - use std::time::Duration; + + use super::*; #[test] fn distant_api_should_support_merging_with_config() { diff --git a/src/options/common/address.rs b/src/options/common/address.rs index 1eadfa9..7fa89cf 100644 --- a/src/options/common/address.rs +++ b/src/options/common/address.rs @@ -1,10 +1,11 @@ +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; +use std::str::FromStr; +use std::{env, fmt}; + use anyhow::Context; use derive_more::IsVariant; use distant_core::net::common::{Host, HostParseError}; use serde::{Deserialize, Serialize}; -use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; -use std::str::FromStr; -use std::{env, fmt}; /// Represents options for binding a server to an IP address. #[derive(Clone, Debug, PartialEq, Eq, IsVariant)] @@ -118,9 +119,10 @@ impl BindAddress { #[cfg(test)] mod tests { - use super::*; use test_log::test; + use super::*; + #[test] fn to_string_should_properly_print_bind_address() { assert_eq!(BindAddress::Any.to_string(), "any"); diff --git a/src/options/common/cmd.rs b/src/options/common/cmd.rs index 78c39c1..45bb0e5 100644 --- a/src/options/common/cmd.rs +++ b/src/options/common/cmd.rs @@ -1,7 +1,8 @@ -use clap::Args; use std::fmt; use std::str::FromStr; +use clap::Args; + /// Represents some command with arguments to execute. /// /// NOTE: Must be derived with `#[clap(flatten)]` to properly take effect. diff --git a/src/options/common/logging.rs b/src/options/common/logging.rs index d653b1f..1c7de01 100644 --- a/src/options/common/logging.rs +++ b/src/options/common/logging.rs @@ -1,6 +1,7 @@ +use std::path::PathBuf; + use clap::{Args, ValueEnum}; use serde::{Deserialize, Serialize}; -use std::path::PathBuf; /// Contains settings are associated with logging. #[derive(Args, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] diff --git a/src/options/common/network.rs b/src/options/common/network.rs index a26879d..80602cf 100644 --- a/src/options/common/network.rs +++ b/src/options/common/network.rs @@ -1,7 +1,8 @@ -use crate::constants; use clap::Args; use serde::{Deserialize, Serialize}; +use crate::constants; + /// Level of access control to the unix socket or windows pipe #[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)] #[clap(rename_all = "snake_case")] diff --git a/src/options/common/search.rs b/src/options/common/search.rs index 9a4abce..643bc46 100644 --- a/src/options/common/search.rs +++ b/src/options/common/search.rs @@ -1,9 +1,8 @@ -use clap::{Args, ValueEnum}; -use distant_core::data::FileType; -use distant_core::data::{SearchQueryOptions, SearchQueryTarget}; use std::collections::HashSet; +use clap::{Args, ValueEnum}; pub use distant_core::data::SearchQueryCondition as CliSearchQueryCondition; +use distant_core::data::{FileType, SearchQueryOptions, SearchQueryTarget}; /// Options to customize the search results. #[derive(Args, Clone, Debug, Default, PartialEq, Eq)] diff --git a/src/options/common/value.rs b/src/options/common/value.rs index 25ee7c0..62f2b10 100644 --- a/src/options/common/value.rs +++ b/src/options/common/value.rs @@ -1,8 +1,9 @@ -use derive_more::{Display, IsVariant}; -use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::ops::{Deref, DerefMut}; use std::str::FromStr; +use derive_more::{Display, IsVariant}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + /// Represents a value for some CLI option or config. This exists to support optional values that /// have a default value so we can distinguish if a CLI value was a default or explicitly defined. #[derive(Copy, Clone, Debug, Display, IsVariant)] diff --git a/src/options/config.rs b/src/options/config.rs index 204525c..e857792 100644 --- a/src/options/config.rs +++ b/src/options/config.rs @@ -1,9 +1,11 @@ -use super::common; -use crate::constants; +use std::path::PathBuf; + use anyhow::Context; use once_cell::sync::Lazy; use serde::{Deserialize, Serialize}; -use std::path::PathBuf; + +use super::common; +use crate::constants; mod client; mod generate; @@ -92,15 +94,17 @@ impl Default for Config { #[cfg(test)] mod tests { - use super::*; + use std::net::Ipv4Addr; + use std::time::Duration; + use common::*; use distant_core::net::common::{Host, Map, PortRange}; use distant_core::net::map; use distant_core::net::server::Shutdown; - use std::net::Ipv4Addr; - use std::time::Duration; use test_log::test; + use super::*; + #[test] fn default_should_parse_config_from_internal_toml() { let config = Config::default(); diff --git a/src/options/config/client.rs b/src/options/config/client.rs index cb8963c..d861ea8 100644 --- a/src/options/config/client.rs +++ b/src/options/config/client.rs @@ -1,6 +1,7 @@ -use super::common::{self, LoggingSettings, NetworkSettings}; use serde::{Deserialize, Serialize}; +use super::common::{self, LoggingSettings, NetworkSettings}; + mod api; mod connect; mod launch; diff --git a/src/options/config/client/launch.rs b/src/options/config/client/launch.rs index 8e22b10..6bdcc09 100644 --- a/src/options/config/client/launch.rs +++ b/src/options/config/client/launch.rs @@ -1,7 +1,8 @@ -use super::common::BindAddress; use distant_core::net::common::Map; use serde::{Deserialize, Serialize}; +use super::common::BindAddress; + #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct ClientLaunchConfig { #[serde(flatten)] diff --git a/src/options/config/generate.rs b/src/options/config/generate.rs index 23602dd..059882c 100644 --- a/src/options/config/generate.rs +++ b/src/options/config/generate.rs @@ -1,6 +1,7 @@ -use super::common::LoggingSettings; use serde::{Deserialize, Serialize}; +use super::common::LoggingSettings; + /// Represents configuration settings for the distant generate #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct GenerateConfig { diff --git a/src/options/config/manager.rs b/src/options/config/manager.rs index 1b78846..5a62bf8 100644 --- a/src/options/config/manager.rs +++ b/src/options/config/manager.rs @@ -1,6 +1,7 @@ -use super::common::{AccessControl, LoggingSettings, NetworkSettings}; use serde::{Deserialize, Serialize}; +use super::common::{AccessControl, LoggingSettings, NetworkSettings}; + /// Represents configuration settings for the distant manager #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct ManagerConfig { diff --git a/src/options/config/server.rs b/src/options/config/server.rs index 416baf9..a2bc437 100644 --- a/src/options/config/server.rs +++ b/src/options/config/server.rs @@ -1,6 +1,7 @@ -use super::common::LoggingSettings; use serde::{Deserialize, Serialize}; +use super::common::LoggingSettings; + mod listen; pub use listen::*; diff --git a/src/options/config/server/listen.rs b/src/options/config/server/listen.rs index 75db704..cebf26a 100644 --- a/src/options/config/server/listen.rs +++ b/src/options/config/server/listen.rs @@ -1,8 +1,10 @@ -use crate::options::BindAddress; +use std::path::PathBuf; + use distant_core::net::common::{Map, PortRange}; use distant_core::net::server::Shutdown; use serde::{Deserialize, Serialize}; -use std::path::PathBuf; + +use crate::options::BindAddress; #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct ServerListenConfig { diff --git a/src/win_service.rs b/src/win_service.rs index b131497..87ec00e 100644 --- a/src/win_service.rs +++ b/src/win_service.rs @@ -1,23 +1,19 @@ -use super::Cli; +use std::ffi::{OsStr, OsString}; +use std::path::Path; +use std::sync::mpsc; +use std::thread; +use std::time::Duration; + use anyhow::Context; use derive_more::From; use log::*; -use std::{ - ffi::{OsStr, OsString}, - path::Path, - sync::mpsc, - thread, - time::Duration, -}; -use windows_service::{ - define_windows_service, - service::{ - ServiceControl, ServiceControlAccept, ServiceExitCode, ServiceState, ServiceStatus, - ServiceType, - }, - service_control_handler::{self, ServiceControlHandlerResult}, - service_dispatcher, +use windows_service::service::{ + ServiceControl, ServiceControlAccept, ServiceExitCode, ServiceState, ServiceStatus, ServiceType, }; +use windows_service::service_control_handler::{self, ServiceControlHandlerResult}; +use windows_service::{define_windows_service, service_dispatcher}; + +use super::Cli; const SERVICE_NAME: &str = "distant_manager"; const SERVICE_TYPE: ServiceType = ServiceType::OWN_PROCESS; diff --git a/tests/cli/api/capabilities.rs b/tests/cli/api/capabilities.rs index f697d5a..076d137 100644 --- a/tests/cli/api/capabilities.rs +++ b/tests/cli/api/capabilities.rs @@ -1,9 +1,10 @@ -use crate::cli::fixtures::*; use distant_core::data::{Capabilities, Capability}; use rstest::*; use serde_json::json; use test_log::test; +use crate::cli::fixtures::*; + #[rstest] #[test(tokio::test)] async fn should_support_json_capabilities(mut api_process: CtxCommand) { diff --git a/tests/cli/api/copy.rs b/tests/cli/api/copy.rs index d026bb7..f6c2978 100644 --- a/tests/cli/api/copy.rs +++ b/tests/cli/api/copy.rs @@ -1,10 +1,11 @@ -use crate::cli::fixtures::*; use assert_fs::prelude::*; use predicates::prelude::*; use rstest::*; use serde_json::json; use test_log::test; +use crate::cli::fixtures::*; + const FILE_CONTENTS: &str = r#" some text on multiple lines diff --git a/tests/cli/api/dir_create.rs b/tests/cli/api/dir_create.rs index 74d33a0..6c30e1f 100644 --- a/tests/cli/api/dir_create.rs +++ b/tests/cli/api/dir_create.rs @@ -1,10 +1,11 @@ -use crate::cli::fixtures::*; use assert_fs::prelude::*; use predicates::prelude::*; use rstest::*; use serde_json::json; use test_log::test; +use crate::cli::fixtures::*; + #[rstest] #[test(tokio::test)] async fn should_support_json_output(mut api_process: CtxCommand) { diff --git a/tests/cli/api/dir_read.rs b/tests/cli/api/dir_read.rs index 9e2a0c8..51c7237 100644 --- a/tests/cli/api/dir_read.rs +++ b/tests/cli/api/dir_read.rs @@ -1,10 +1,12 @@ -use crate::cli::fixtures::*; +use std::path::PathBuf; + use assert_fs::prelude::*; use rstest::*; use serde_json::json; -use std::path::PathBuf; use test_log::test; +use crate::cli::fixtures::*; + /// Creates a directory in the form /// /// $TEMP/ diff --git a/tests/cli/api/exists.rs b/tests/cli/api/exists.rs index f3a2492..5e4876b 100644 --- a/tests/cli/api/exists.rs +++ b/tests/cli/api/exists.rs @@ -1,9 +1,10 @@ -use crate::cli::fixtures::*; use assert_fs::prelude::*; use rstest::*; use serde_json::json; use test_log::test; +use crate::cli::fixtures::*; + #[rstest] #[test(tokio::test)] async fn should_support_json_true_if_exists(mut api_process: CtxCommand) { diff --git a/tests/cli/api/file_append.rs b/tests/cli/api/file_append.rs index ad01d4b..a0768ed 100644 --- a/tests/cli/api/file_append.rs +++ b/tests/cli/api/file_append.rs @@ -1,9 +1,10 @@ -use crate::cli::fixtures::*; use assert_fs::prelude::*; use rstest::*; use serde_json::json; use test_log::test; +use crate::cli::fixtures::*; + const FILE_CONTENTS: &str = r#" some text on multiple lines diff --git a/tests/cli/api/file_append_text.rs b/tests/cli/api/file_append_text.rs index 035a153..6956724 100644 --- a/tests/cli/api/file_append_text.rs +++ b/tests/cli/api/file_append_text.rs @@ -1,9 +1,10 @@ -use crate::cli::fixtures::*; use assert_fs::prelude::*; use rstest::*; use serde_json::json; use test_log::test; +use crate::cli::fixtures::*; + const FILE_CONTENTS: &str = r#" some text on multiple lines diff --git a/tests/cli/api/file_read.rs b/tests/cli/api/file_read.rs index aefa57e..5b68f27 100644 --- a/tests/cli/api/file_read.rs +++ b/tests/cli/api/file_read.rs @@ -1,9 +1,10 @@ -use crate::cli::fixtures::*; use assert_fs::prelude::*; use rstest::*; use serde_json::json; use test_log::test; +use crate::cli::fixtures::*; + const FILE_CONTENTS: &str = r#" some text on multiple lines diff --git a/tests/cli/api/file_read_text.rs b/tests/cli/api/file_read_text.rs index 2ff5315..2866fd5 100644 --- a/tests/cli/api/file_read_text.rs +++ b/tests/cli/api/file_read_text.rs @@ -1,9 +1,10 @@ -use crate::cli::fixtures::*; use assert_fs::prelude::*; use rstest::*; use serde_json::json; use test_log::test; +use crate::cli::fixtures::*; + const FILE_CONTENTS: &str = r#" some text on multiple lines diff --git a/tests/cli/api/file_write.rs b/tests/cli/api/file_write.rs index fd0c388..124557d 100644 --- a/tests/cli/api/file_write.rs +++ b/tests/cli/api/file_write.rs @@ -1,9 +1,10 @@ -use crate::cli::fixtures::*; use assert_fs::prelude::*; use rstest::*; use serde_json::json; use test_log::test; +use crate::cli::fixtures::*; + const FILE_CONTENTS: &str = r#" some text on multiple lines diff --git a/tests/cli/api/file_write_text.rs b/tests/cli/api/file_write_text.rs index 76b834e..718aa92 100644 --- a/tests/cli/api/file_write_text.rs +++ b/tests/cli/api/file_write_text.rs @@ -1,9 +1,10 @@ -use crate::cli::fixtures::*; use assert_fs::prelude::*; use rstest::*; use serde_json::json; use test_log::test; +use crate::cli::fixtures::*; + const FILE_CONTENTS: &str = r#" some text on multiple lines diff --git a/tests/cli/api/metadata.rs b/tests/cli/api/metadata.rs index 1bc6369..727a341 100644 --- a/tests/cli/api/metadata.rs +++ b/tests/cli/api/metadata.rs @@ -1,9 +1,10 @@ -use crate::cli::fixtures::*; use assert_fs::prelude::*; use rstest::*; use serde_json::{json, Value}; use test_log::test; +use crate::cli::fixtures::*; + const FILE_CONTENTS: &str = r#" some text on multiple lines diff --git a/tests/cli/api/proc_spawn.rs b/tests/cli/api/proc_spawn.rs index 1ec5b99..e8be958 100644 --- a/tests/cli/api/proc_spawn.rs +++ b/tests/cli/api/proc_spawn.rs @@ -1,8 +1,10 @@ -use crate::cli::{fixtures::*, scripts::*}; use rstest::*; use serde_json::json; use test_log::test; +use crate::cli::fixtures::*; +use crate::cli::scripts::*; + fn make_cmd(args: Vec<&str>) -> String { format!( r#"{} {} {}"#, diff --git a/tests/cli/api/remove.rs b/tests/cli/api/remove.rs index a6f56ca..c115105 100644 --- a/tests/cli/api/remove.rs +++ b/tests/cli/api/remove.rs @@ -1,10 +1,11 @@ -use crate::cli::fixtures::*; use assert_fs::prelude::*; use predicates::prelude::*; use rstest::*; use serde_json::json; use test_log::test; +use crate::cli::fixtures::*; + #[rstest] #[test(tokio::test)] async fn should_support_json_removing_file(mut api_process: CtxCommand) { diff --git a/tests/cli/api/rename.rs b/tests/cli/api/rename.rs index adf23d8..6107d92 100644 --- a/tests/cli/api/rename.rs +++ b/tests/cli/api/rename.rs @@ -1,10 +1,11 @@ -use crate::cli::fixtures::*; use assert_fs::prelude::*; use predicates::prelude::*; use rstest::*; use serde_json::json; use test_log::test; +use crate::cli::fixtures::*; + const FILE_CONTENTS: &str = r#" some text on multiple lines diff --git a/tests/cli/api/search.rs b/tests/cli/api/search.rs index 1dfe9fa..05752e8 100644 --- a/tests/cli/api/search.rs +++ b/tests/cli/api/search.rs @@ -1,9 +1,10 @@ -use crate::cli::fixtures::*; use assert_fs::prelude::*; use rstest::*; use serde_json::json; use test_log::test; +use crate::cli::fixtures::*; + #[rstest] #[test(tokio::test)] async fn should_support_json_search_filesystem_using_query( diff --git a/tests/cli/api/system_info.rs b/tests/cli/api/system_info.rs index 0e597e7..19d4695 100644 --- a/tests/cli/api/system_info.rs +++ b/tests/cli/api/system_info.rs @@ -1,9 +1,11 @@ -use crate::cli::fixtures::*; +use std::env; + use rstest::*; use serde_json::json; -use std::env; use test_log::test; +use crate::cli::fixtures::*; + #[rstest] #[test(tokio::test)] async fn should_support_json_system_info(mut api_process: CtxCommand) { diff --git a/tests/cli/api/watch.rs b/tests/cli/api/watch.rs index e71c786..d3a02f6 100644 --- a/tests/cli/api/watch.rs +++ b/tests/cli/api/watch.rs @@ -1,10 +1,12 @@ -use crate::cli::fixtures::*; +use std::time::Duration; + use assert_fs::prelude::*; use rstest::*; use serde_json::json; -use std::time::Duration; use test_log::test; +use crate::cli::fixtures::*; + async fn wait_a_bit() { wait_millis(250).await; } diff --git a/tests/cli/client/capabilities.rs b/tests/cli/client/capabilities.rs index 1996b99..c12adff 100644 --- a/tests/cli/client/capabilities.rs +++ b/tests/cli/client/capabilities.rs @@ -1,7 +1,8 @@ -use crate::cli::fixtures::*; use indoc::indoc; use rstest::*; +use crate::cli::fixtures::*; + const EXPECTED_TABLE: &str = indoc! {" +------------------+------------------------------------------------------------------+ | kind | description | diff --git a/tests/cli/client/fs_copy.rs b/tests/cli/client/fs_copy.rs index a7b0344..9e5d493 100644 --- a/tests/cli/client/fs_copy.rs +++ b/tests/cli/client/fs_copy.rs @@ -1,8 +1,9 @@ -use crate::cli::fixtures::*; use assert_fs::prelude::*; use predicates::prelude::*; use rstest::*; +use crate::cli::fixtures::*; + const FILE_CONTENTS: &str = r#" some text on multiple lines diff --git a/tests/cli/client/fs_exists.rs b/tests/cli/client/fs_exists.rs index 8ff9c58..51deac9 100644 --- a/tests/cli/client/fs_exists.rs +++ b/tests/cli/client/fs_exists.rs @@ -1,7 +1,8 @@ -use crate::cli::fixtures::*; use assert_fs::prelude::*; use rstest::*; +use crate::cli::fixtures::*; + #[rstest] #[test_log::test] fn should_output_true_if_exists(ctx: DistantManagerCtx) { diff --git a/tests/cli/client/fs_make_dir.rs b/tests/cli/client/fs_make_dir.rs index a1cb72f..56f68b2 100644 --- a/tests/cli/client/fs_make_dir.rs +++ b/tests/cli/client/fs_make_dir.rs @@ -1,8 +1,9 @@ -use crate::cli::fixtures::*; use assert_fs::prelude::*; use predicates::prelude::*; use rstest::*; +use crate::cli::fixtures::*; + #[rstest] #[test_log::test] fn should_report_ok_when_done(ctx: DistantManagerCtx) { diff --git a/tests/cli/client/fs_metadata.rs b/tests/cli/client/fs_metadata.rs index d09fa89..fbf500a 100644 --- a/tests/cli/client/fs_metadata.rs +++ b/tests/cli/client/fs_metadata.rs @@ -1,8 +1,10 @@ -use crate::cli::{fixtures::*, utils::regex_pred}; use assert_fs::prelude::*; use predicates::prelude::*; use rstest::*; +use crate::cli::fixtures::*; +use crate::cli::utils::regex_pred; + const FILE_CONTENTS: &str = r#" some text on multiple lines diff --git a/tests/cli/client/fs_read_directory.rs b/tests/cli/client/fs_read_directory.rs index 8f65314..667c819 100644 --- a/tests/cli/client/fs_read_directory.rs +++ b/tests/cli/client/fs_read_directory.rs @@ -1,8 +1,11 @@ -use crate::cli::{fixtures::*, utils::regex_pred}; +use std::path::Path; + use assert_fs::prelude::*; use predicates::prelude::*; use rstest::*; -use std::path::Path; + +use crate::cli::fixtures::*; +use crate::cli::utils::regex_pred; /// Creates a directory in the form /// diff --git a/tests/cli/client/fs_read_file.rs b/tests/cli/client/fs_read_file.rs index 931481e..e0eed40 100644 --- a/tests/cli/client/fs_read_file.rs +++ b/tests/cli/client/fs_read_file.rs @@ -1,9 +1,10 @@ -use crate::cli::fixtures::*; use assert_fs::prelude::*; use indoc::indoc; use predicates::prelude::*; use rstest::*; +use crate::cli::fixtures::*; + const FILE_CONTENTS: &str = indoc! {r#" some text on multiple lines diff --git a/tests/cli/client/fs_remove.rs b/tests/cli/client/fs_remove.rs index e68c3e5..29e1fa1 100644 --- a/tests/cli/client/fs_remove.rs +++ b/tests/cli/client/fs_remove.rs @@ -1,8 +1,9 @@ -use crate::cli::fixtures::*; use assert_fs::prelude::*; use predicates::prelude::*; use rstest::*; +use crate::cli::fixtures::*; + #[rstest] #[test_log::test] fn should_support_removing_file(ctx: DistantManagerCtx) { diff --git a/tests/cli/client/fs_rename.rs b/tests/cli/client/fs_rename.rs index 9ba8e80..806add4 100644 --- a/tests/cli/client/fs_rename.rs +++ b/tests/cli/client/fs_rename.rs @@ -1,8 +1,9 @@ -use crate::cli::fixtures::*; use assert_fs::prelude::*; use predicates::prelude::*; use rstest::*; +use crate::cli::fixtures::*; + const FILE_CONTENTS: &str = r#" some text on multiple lines diff --git a/tests/cli/client/fs_search.rs b/tests/cli/client/fs_search.rs index 6a62e14..77f7b52 100644 --- a/tests/cli/client/fs_search.rs +++ b/tests/cli/client/fs_search.rs @@ -1,9 +1,10 @@ -use crate::cli::fixtures::*; use assert_fs::prelude::*; use indoc::indoc; use predicates::Predicate; use rstest::*; +use crate::cli::fixtures::*; + const SEARCH_RESULTS_REGEX: &str = indoc! {r" .*?[\\/]file1.txt 1:some file text diff --git a/tests/cli/client/fs_watch.rs b/tests/cli/client/fs_watch.rs index 3e632c8..0a7a89f 100644 --- a/tests/cli/client/fs_watch.rs +++ b/tests/cli/client/fs_watch.rs @@ -1,7 +1,11 @@ -use crate::cli::{fixtures::*, utils::ThreadedReader}; +use std::thread; +use std::time::Duration; + use assert_fs::prelude::*; use rstest::*; -use std::{thread, time::Duration}; + +use crate::cli::fixtures::*; +use crate::cli::utils::ThreadedReader; fn wait_a_bit() { wait_millis(250); diff --git a/tests/cli/client/fs_write.rs b/tests/cli/client/fs_write.rs index 5af4356..411d34d 100644 --- a/tests/cli/client/fs_write.rs +++ b/tests/cli/client/fs_write.rs @@ -1,9 +1,10 @@ -use crate::cli::fixtures::*; use assert_fs::prelude::*; use indoc::indoc; use predicates::prelude::*; use rstest::*; +use crate::cli::fixtures::*; + const FILE_CONTENTS: &str = indoc! {r#" some text on multiple lines diff --git a/tests/cli/client/spawn.rs b/tests/cli/client/spawn.rs index c5b86b1..183a55a 100644 --- a/tests/cli/client/spawn.rs +++ b/tests/cli/client/spawn.rs @@ -1,6 +1,9 @@ -use crate::cli::{fixtures::*, scripts::*, utils::regex_pred}; use rstest::*; +use crate::cli::fixtures::*; +use crate::cli::scripts::*; +use crate::cli::utils::regex_pred; + #[rstest] #[test_log::test] fn should_execute_program_and_return_exit_status(ctx: DistantManagerCtx) { diff --git a/tests/cli/client/system_info.rs b/tests/cli/client/system_info.rs index cf44c46..58c2158 100644 --- a/tests/cli/client/system_info.rs +++ b/tests/cli/client/system_info.rs @@ -1,7 +1,9 @@ -use crate::cli::fixtures::*; -use rstest::*; use std::env; +use rstest::*; + +use crate::cli::fixtures::*; + #[rstest] #[test_log::test] fn should_output_system_info(ctx: DistantManagerCtx) { diff --git a/tests/cli/fixtures.rs b/tests/cli/fixtures.rs index 03f91af..2230467 100644 --- a/tests/cli/fixtures.rs +++ b/tests/cli/fixtures.rs @@ -1,17 +1,17 @@ +use std::io::{BufReader, Read}; +use std::net::{Ipv4Addr, Ipv6Addr}; +use std::path::PathBuf; +use std::process::{Child, Command as StdCommand, Stdio}; +use std::thread; +use std::time::{Duration, Instant}; + use assert_cmd::Command; use derive_more::{Deref, DerefMut}; -use distant_core::{net::common::Host, DistantSingleKeyCredentials}; +use distant_core::net::common::Host; +use distant_core::DistantSingleKeyCredentials; use once_cell::sync::Lazy; use rstest::*; use serde_json::json; -use std::{ - io::{BufReader, Read}, - net::{Ipv4Addr, Ipv6Addr}, - path::PathBuf, - process::{Child, Command as StdCommand, Stdio}, - thread, - time::{Duration, Instant}, -}; mod api; pub use api::ApiProcess; diff --git a/tests/cli/fixtures/api.rs b/tests/cli/fixtures/api.rs index fd9e451..6ceb901 100644 --- a/tests/cli/fixtures/api.rs +++ b/tests/cli/fixtures/api.rs @@ -1,10 +1,9 @@ +use std::io::{self, BufRead, BufReader, BufWriter, Write}; +use std::process::Child; +use std::thread; +use std::time::Duration; + use serde_json::Value; -use std::{ - io::{self, BufRead, BufReader, BufWriter, Write}, - process::Child, - thread, - time::Duration, -}; use tokio::sync::mpsc; const CHANNEL_BUFFER: usize = 100; diff --git a/tests/cli/manager/capabilities.rs b/tests/cli/manager/capabilities.rs index bb2b862..61568fc 100644 --- a/tests/cli/manager/capabilities.rs +++ b/tests/cli/manager/capabilities.rs @@ -1,7 +1,8 @@ -use crate::cli::fixtures::*; use indoc::indoc; use rstest::*; +use crate::cli::fixtures::*; + const EXPECTED_TABLE: &str = indoc! {" +---------------+--------------------------------------------------------------+ | kind | description | diff --git a/tests/cli/utils/reader.rs b/tests/cli/utils/reader.rs index b7ab94c..3b3cede 100644 --- a/tests/cli/utils/reader.rs +++ b/tests/cli/utils/reader.rs @@ -1,10 +1,7 @@ -use std::{ - io, - io::{BufRead, BufReader, Read}, - sync::mpsc, - thread, - time::{Duration, Instant}, -}; +use std::io::{BufRead, BufReader, Read}; +use std::sync::mpsc; +use std::time::{Duration, Instant}; +use std::{io, thread}; pub struct ThreadedReader { #[allow(dead_code)]