Optimized code and performance using clippy

This commit is contained in:
ChristianVisintin
2020-12-12 12:14:51 +01:00
parent 0eae159bb9
commit 55bda874f0
16 changed files with 716 additions and 772 deletions
+1 -1
View File
@@ -30,7 +30,7 @@ regex = "1.4.2"
lazy_static = "1.4.0" lazy_static = "1.4.0"
hostname = "0.3.1" hostname = "0.3.1"
[target.'cfg(any(unix, macos, linux))'.dependencies] [target.'cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))'.dependencies]
users = "0.11.0" users = "0.11.0"
[dev-dependencies] [dev-dependencies]
+6 -6
View File
@@ -73,7 +73,7 @@ impl ActivityManager {
Ok(ActivityManager { Ok(ActivityManager {
context: Some(ctx), context: Some(ctx),
ftparams: None, ftparams: None,
interval: interval, interval,
}) })
} }
@@ -89,11 +89,11 @@ impl ActivityManager {
password: Option<String>, password: Option<String>,
) { ) {
self.ftparams = Some(FileTransferParams { self.ftparams = Some(FileTransferParams {
address: address, address,
port: port, port,
protocol: protocol, protocol,
username: username, username,
password: password, password,
}); });
} }
+10 -19
View File
@@ -53,10 +53,7 @@ impl FtpFileTransfer {
/// ///
/// Instantiates a new `FtpFileTransfer` /// Instantiates a new `FtpFileTransfer`
pub fn new(ftps: bool) -> FtpFileTransfer { pub fn new(ftps: bool) -> FtpFileTransfer {
FtpFileTransfer { FtpFileTransfer { stream: None, ftps }
stream: None,
ftps: ftps,
}
} }
/// ### parse_list_line /// ### parse_list_line
@@ -97,8 +94,7 @@ impl FtpFileTransfer {
match c { match c {
'-' => {} '-' => {}
_ => { _ => {
count = count count += match i {
+ match i {
0 => 4, 0 => 4,
1 => 2, 1 => 2,
2 => 1, 2 => 1,
@@ -115,8 +111,7 @@ impl FtpFileTransfer {
match c { match c {
'-' => {} '-' => {}
_ => { _ => {
count = count count += match i {
+ match i {
0 => 4, 0 => 4,
1 => 2, 1 => 2,
2 => 1, 2 => 1,
@@ -133,8 +128,7 @@ impl FtpFileTransfer {
match c { match c {
'-' => {} '-' => {}
_ => { _ => {
count = count count += match i {
+ match i {
0 => 4, 0 => 4,
1 => 2, 1 => 2,
2 => 1, 2 => 1,
@@ -174,7 +168,7 @@ impl FtpFileTransfer {
let file_name: String = String::from(metadata.get(8).unwrap().as_str()); let file_name: String = String::from(metadata.get(8).unwrap().as_str());
// Check if file_name is '.' or '..' // Check if file_name is '.' or '..'
if file_name.as_str() == "." || file_name.as_str() == ".." { if file_name.as_str() == "." || file_name.as_str() == ".." {
return Err(()) return Err(());
} }
let mut abs_path: PathBuf = PathBuf::from(path); let mut abs_path: PathBuf = PathBuf::from(path);
let extension: Option<String> = match abs_path.as_path().extension() { let extension: Option<String> = match abs_path.as_path().extension() {
@@ -187,7 +181,7 @@ impl FtpFileTransfer {
Ok(match is_dir { Ok(match is_dir {
true => FsEntry::Directory(FsDirectory { true => FsEntry::Directory(FsDirectory {
name: file_name, name: file_name,
abs_path: abs_path, abs_path,
last_change_time: mtime, last_change_time: mtime,
last_access_time: mtime, last_access_time: mtime,
creation_time: mtime, creation_time: mtime,
@@ -199,7 +193,7 @@ impl FtpFileTransfer {
}), }),
false => FsEntry::File(FsFile { false => FsEntry::File(FsFile {
name: file_name, name: file_name,
abs_path: abs_path, abs_path,
last_change_time: mtime, last_change_time: mtime,
last_access_time: mtime, last_access_time: mtime,
creation_time: mtime, creation_time: mtime,
@@ -267,11 +261,11 @@ impl FileTransfer for FtpFileTransfer {
} }
// Login (use anonymous if credentials are unspecified) // Login (use anonymous if credentials are unspecified)
let username: String = match username { let username: String = match username {
Some(u) => u.clone(), Some(u) => u,
None => String::from("anonymous"), None => String::from("anonymous"),
}; };
let password: String = match password { let password: String = match password {
Some(pwd) => String::from(pwd), Some(pwd) => pwd,
None => String::new(), None => String::new(),
}; };
if let Err(err) = stream.login(username.as_str(), password.as_str()) { if let Err(err) = stream.login(username.as_str(), password.as_str()) {
@@ -309,10 +303,7 @@ impl FileTransfer for FtpFileTransfer {
/// ///
/// Indicates whether the client is connected to remote /// Indicates whether the client is connected to remote
fn is_connected(&self) -> bool { fn is_connected(&self) -> bool {
match self.stream { self.stream.is_some()
Some(_) => true,
None => false,
}
} }
/// ### pwd /// ### pwd
+1 -1
View File
@@ -79,7 +79,7 @@ impl FileTransferError {
/// Instantiates a new FileTransferError /// Instantiates a new FileTransferError
pub fn new(code: FileTransferErrorType) -> FileTransferError { pub fn new(code: FileTransferErrorType) -> FileTransferError {
FileTransferError { FileTransferError {
code: code, code,
msg: None, msg: None,
} }
} }
+18 -18
View File
@@ -48,6 +48,12 @@ pub struct ScpFileTransfer {
wrkdir: PathBuf, wrkdir: PathBuf,
} }
impl Default for ScpFileTransfer {
fn default() -> Self {
Self::new()
}
}
impl ScpFileTransfer { impl ScpFileTransfer {
/// ### new /// ### new
/// ///
@@ -97,8 +103,7 @@ impl ScpFileTransfer {
match c { match c {
'-' => {} '-' => {}
_ => { _ => {
count = count count += match i {
+ match i {
0 => 4, 0 => 4,
1 => 2, 1 => 2,
2 => 1, 2 => 1,
@@ -115,8 +120,7 @@ impl ScpFileTransfer {
match c { match c {
'-' => {} '-' => {}
_ => { _ => {
count = count count += match i {
+ match i {
0 => 4, 0 => 4,
1 => 2, 1 => 2,
2 => 1, 2 => 1,
@@ -133,8 +137,7 @@ impl ScpFileTransfer {
match c { match c {
'-' => {} '-' => {}
_ => { _ => {
count = count count += match i {
+ match i {
0 => 4, 0 => 4,
1 => 2, 1 => 2,
2 => 1, 2 => 1,
@@ -178,7 +181,7 @@ impl ScpFileTransfer {
}; };
// Check if file_name is '.' or '..' // Check if file_name is '.' or '..'
if file_name.as_str() == "." || file_name.as_str() == ".." { if file_name.as_str() == "." || file_name.as_str() == ".." {
return Err(()) return Err(());
} }
let mut abs_path: PathBuf = PathBuf::from(path); let mut abs_path: PathBuf = PathBuf::from(path);
let extension: Option<String> = match abs_path.as_path().extension() { let extension: Option<String> = match abs_path.as_path().extension() {
@@ -191,7 +194,7 @@ impl ScpFileTransfer {
Ok(match is_dir { Ok(match is_dir {
true => FsEntry::Directory(FsDirectory { true => FsEntry::Directory(FsDirectory {
name: file_name, name: file_name,
abs_path: abs_path, abs_path,
last_change_time: mtime, last_change_time: mtime,
last_access_time: mtime, last_access_time: mtime,
creation_time: mtime, creation_time: mtime,
@@ -203,7 +206,7 @@ impl ScpFileTransfer {
}), }),
false => FsEntry::File(FsFile { false => FsEntry::File(FsFile {
name: file_name, name: file_name,
abs_path: abs_path, abs_path,
last_change_time: mtime, last_change_time: mtime,
last_access_time: mtime, last_access_time: mtime,
creation_time: mtime, creation_time: mtime,
@@ -331,15 +334,15 @@ impl FileTransfer for ScpFileTransfer {
)); ));
} }
let username: String = match username { let username: String = match username {
Some(u) => u.clone(), Some(u) => u,
None => String::from(""), None => String::from(""),
}; };
// Try authenticating with user agent // Try authenticating with user agent
if let Err(_) = session.userauth_agent(username.as_str()) { if session.userauth_agent(username.as_str()).is_err() {
// Try authentication with password then // Try authentication with password then
if let Err(err) = session.userauth_password( if let Err(err) = session.userauth_password(
username.as_str(), username.as_str(),
password.unwrap_or(String::from("")).as_str(), password.unwrap_or_else(|| String::from("")).as_str(),
) { ) {
return Err(FileTransferError::new_ex( return Err(FileTransferError::new_ex(
FileTransferErrorType::AuthenticationFailed, FileTransferErrorType::AuthenticationFailed,
@@ -391,10 +394,7 @@ impl FileTransfer for ScpFileTransfer {
/// ///
/// Indicates whether the client is connected to remote /// Indicates whether the client is connected to remote
fn is_connected(&self) -> bool { fn is_connected(&self) -> bool {
match self.session.as_ref() { self.session.as_ref().is_some()
Some(_) => true,
None => false,
}
} }
/// ### pwd /// ### pwd
@@ -435,7 +435,7 @@ impl FileTransfer for ScpFileTransfer {
// Trim // Trim
let output: String = String::from(output.as_str().trim()); let output: String = String::from(output.as_str().trim());
// Check if output starts with 0; should be 0{PWD} // Check if output starts with 0; should be 0{PWD}
match output.as_str().starts_with("0") { match output.as_str().starts_with('0') {
true => { true => {
// Set working directory // Set working directory
self.wrkdir = PathBuf::from(&output.as_str()[1..].trim()); self.wrkdir = PathBuf::from(&output.as_str()[1..].trim());
@@ -857,7 +857,7 @@ mod tests {
} }
#[test] #[test]
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
fn test_filetransfer_scp_cwd() { fn test_filetransfer_scp_cwd() {
let mut client: ScpFileTransfer = ScpFileTransfer::new(); let mut client: ScpFileTransfer = ScpFileTransfer::new();
assert!(client assert!(client
+15 -11
View File
@@ -46,6 +46,12 @@ pub struct SftpFileTransfer {
wrkdir: PathBuf, wrkdir: PathBuf,
} }
impl Default for SftpFileTransfer {
fn default() -> Self {
Self::new()
}
}
impl SftpFileTransfer { impl SftpFileTransfer {
/// ### new /// ### new
/// ///
@@ -68,7 +74,7 @@ impl SftpFileTransfer {
root.push(p); root.push(p);
match self.sftp.as_ref().unwrap().realpath(root.as_path()) { match self.sftp.as_ref().unwrap().realpath(root.as_path()) {
Ok(p) => match self.sftp.as_ref().unwrap().stat(p.as_path()) { Ok(p) => match self.sftp.as_ref().unwrap().stat(p.as_path()) {
Ok(_) => Ok(PathBuf::from(p)), Ok(_) => Ok(p),
Err(err) => Err(FileTransferError::new_ex( Err(err) => Err(FileTransferError::new_ex(
FileTransferErrorType::NoSuchFileOrDirectory, FileTransferErrorType::NoSuchFileOrDirectory,
format!("{}", err), format!("{}", err),
@@ -82,7 +88,7 @@ impl SftpFileTransfer {
} }
false => match self.sftp.as_ref().unwrap().realpath(p) { false => match self.sftp.as_ref().unwrap().realpath(p) {
Ok(p) => match self.sftp.as_ref().unwrap().stat(p.as_path()) { Ok(p) => match self.sftp.as_ref().unwrap().stat(p.as_path()) {
Ok(_) => Ok(PathBuf::from(p)), Ok(_) => Ok(p),
Err(err) => Err(FileTransferError::new_ex( Err(err) => Err(FileTransferError::new_ex(
FileTransferErrorType::NoSuchFileOrDirectory, FileTransferErrorType::NoSuchFileOrDirectory,
format!("{}", err), format!("{}", err),
@@ -162,7 +168,7 @@ impl SftpFileTransfer {
last_access_time: atime, last_access_time: atime,
creation_time: SystemTime::UNIX_EPOCH, creation_time: SystemTime::UNIX_EPOCH,
readonly: false, readonly: false,
symlink: symlink, symlink,
user: uid, user: uid,
group: gid, group: gid,
unix_pex: pex, unix_pex: pex,
@@ -176,7 +182,7 @@ impl SftpFileTransfer {
last_access_time: atime, last_access_time: atime,
creation_time: SystemTime::UNIX_EPOCH, creation_time: SystemTime::UNIX_EPOCH,
readonly: false, readonly: false,
symlink: symlink, symlink,
user: uid, user: uid,
group: gid, group: gid,
unix_pex: pex, unix_pex: pex,
@@ -226,15 +232,15 @@ impl FileTransfer for SftpFileTransfer {
)); ));
} }
let username: String = match username { let username: String = match username {
Some(u) => u.clone(), Some(u) => u,
None => String::from(""), None => String::from(""),
}; };
// Try authenticating with user agent // Try authenticating with user agent
if let Err(_) = session.userauth_agent(username.as_str()) { if session.userauth_agent(username.as_str()).is_err() {
// Try authentication with password then // Try authentication with password then
if let Err(err) = session.userauth_password( if let Err(err) = session.userauth_password(
username.as_str(), username.as_str(),
password.unwrap_or(String::from("")).as_str(), password.unwrap_or_else(|| String::from("")).as_str(),
) { ) {
return Err(FileTransferError::new_ex( return Err(FileTransferError::new_ex(
FileTransferErrorType::AuthenticationFailed, FileTransferErrorType::AuthenticationFailed,
@@ -352,12 +358,10 @@ impl FileTransfer for SftpFileTransfer {
}; };
// Get files // Get files
match sftp.readdir(dir.as_path()) { match sftp.readdir(dir.as_path()) {
Err(err) => { Err(err) => Err(FileTransferError::new_ex(
return Err(FileTransferError::new_ex(
FileTransferErrorType::DirStatFailed, FileTransferErrorType::DirStatFailed,
format!("{}", err), format!("{}", err),
)) )),
}
Ok(files) => { Ok(files) => {
// Allocate vector // Allocate vector
let mut entries: Vec<FsEntry> = Vec::with_capacity(files.len()); let mut entries: Vec<FsEntry> = Vec::with_capacity(files.len());
+3 -3
View File
@@ -24,7 +24,7 @@
*/ */
extern crate bytesize; extern crate bytesize;
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
extern crate users; extern crate users;
use crate::utils::{fmt_pex, time_to_str}; use crate::utils::{fmt_pex, time_to_str};
@@ -32,7 +32,7 @@ use crate::utils::{fmt_pex, time_to_str};
use bytesize::ByteSize; use bytesize::ByteSize;
use std::path::PathBuf; use std::path::PathBuf;
use std::time::SystemTime; use std::time::SystemTime;
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
use users::get_user_by_uid; use users::get_user_by_uid;
/// ## FsEntry /// ## FsEntry
@@ -87,7 +87,7 @@ impl std::fmt::Display for FsEntry {
/// ### fmt_ls /// ### fmt_ls
/// ///
/// Format File Entry as `ls` does /// Format File Entry as `ls` does
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self { match self {
FsEntry::Directory(dir) => { FsEntry::Directory(dir) => {
+25 -25
View File
@@ -27,7 +27,7 @@ use std::fs::{self, File, Metadata, OpenOptions};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::time::SystemTime; use std::time::SystemTime;
// Metadata ext // Metadata ext
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
use std::os::unix::fs::MetadataExt; use std::os::unix::fs::MetadataExt;
// Locals // Locals
@@ -62,7 +62,7 @@ impl HostError {
/// Instantiates a new HostError /// Instantiates a new HostError
pub(crate) fn new(error: HostErrorType, errno: Option<std::io::Error>) -> HostError { pub(crate) fn new(error: HostErrorType, errno: Option<std::io::Error>) -> HostError {
HostError { HostError {
error: error, error,
ioerr: errno, ioerr: errno,
} }
} }
@@ -101,7 +101,7 @@ impl Localhost {
/// Instantiates a new Localhost struct /// Instantiates a new Localhost struct
pub fn new(wrkdir: PathBuf) -> Result<Localhost, HostError> { pub fn new(wrkdir: PathBuf) -> Result<Localhost, HostError> {
let mut host: Localhost = Localhost { let mut host: Localhost = Localhost {
wrkdir: wrkdir, wrkdir,
files: Vec::new(), files: Vec::new(),
}; };
// Check if dir exists // Check if dir exists
@@ -264,9 +264,9 @@ impl Localhost {
/// ### stat /// ### stat
/// ///
/// Stat file and create a FsEntry /// Stat file and create a FsEntry
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
pub fn stat(&self, path: &Path) -> Result<FsEntry, HostError> { pub fn stat(&self, path: &Path) -> Result<FsEntry, HostError> {
let attr: Metadata = match fs::metadata(path.clone()) { let attr: Metadata = match fs::metadata(path) {
Ok(metadata) => metadata, Ok(metadata) => metadata,
Err(err) => return Err(HostError::new(HostErrorType::FileNotAccessible, Some(err))), Err(err) => return Err(HostError::new(HostErrorType::FileNotAccessible, Some(err))),
}; };
@@ -436,7 +436,7 @@ impl Localhost {
/// ### u32_to_mode /// ### u32_to_mode
/// ///
/// Return string with format xxxxxx to tuple of permissions (user, group, others) /// Return string with format xxxxxx to tuple of permissions (user, group, others)
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
fn u32_to_mode(&self, mode: u32) -> (u8, u8, u8) { fn u32_to_mode(&self, mode: u32) -> (u8, u8, u8) {
let user: u8 = ((mode >> 6) & 0x7) as u8; let user: u8 = ((mode >> 6) & 0x7) as u8;
let group: u8 = ((mode >> 3) & 0x7) as u8; let group: u8 = ((mode >> 3) & 0x7) as u8;
@@ -449,12 +449,12 @@ impl Localhost {
mod tests { mod tests {
use super::*; use super::*;
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
use std::fs::File; use std::fs::File;
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
use std::io::Write; use std::io::Write;
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
use std::os::unix::fs::{symlink, PermissionsExt}; use std::os::unix::fs::{symlink, PermissionsExt};
#[test] #[test]
@@ -465,7 +465,7 @@ mod tests {
} }
#[test] #[test]
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
fn test_host_localhost_new() { fn test_host_localhost_new() {
let host: Localhost = Localhost::new(PathBuf::from("/bin")).ok().unwrap(); let host: Localhost = Localhost::new(PathBuf::from("/bin")).ok().unwrap();
assert_eq!(host.wrkdir, PathBuf::from("/bin")); assert_eq!(host.wrkdir, PathBuf::from("/bin"));
@@ -501,14 +501,14 @@ mod tests {
} }
#[test] #[test]
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
fn test_host_localhost_pwd() { fn test_host_localhost_pwd() {
let host: Localhost = Localhost::new(PathBuf::from("/bin")).ok().unwrap(); let host: Localhost = Localhost::new(PathBuf::from("/bin")).ok().unwrap();
assert_eq!(host.pwd(), PathBuf::from("/bin")); assert_eq!(host.pwd(), PathBuf::from("/bin"));
} }
#[test] #[test]
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
fn test_host_localhost_list_files() { fn test_host_localhost_list_files() {
let host: Localhost = Localhost::new(PathBuf::from("/bin")).ok().unwrap(); let host: Localhost = Localhost::new(PathBuf::from("/bin")).ok().unwrap();
// Scan dir // Scan dir
@@ -521,7 +521,7 @@ mod tests {
} }
#[test] #[test]
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
fn test_host_localhost_change_dir() { fn test_host_localhost_change_dir() {
let mut host: Localhost = Localhost::new(PathBuf::from("/dev")).ok().unwrap(); let mut host: Localhost = Localhost::new(PathBuf::from("/dev")).ok().unwrap();
let new_dir: PathBuf = PathBuf::from("/dev"); let new_dir: PathBuf = PathBuf::from("/dev");
@@ -537,7 +537,7 @@ mod tests {
} }
#[test] #[test]
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
#[should_panic] #[should_panic]
fn test_host_localhost_change_dir_failed() { fn test_host_localhost_change_dir_failed() {
let mut host: Localhost = Localhost::new(PathBuf::from("/bin")).ok().unwrap(); let mut host: Localhost = Localhost::new(PathBuf::from("/bin")).ok().unwrap();
@@ -546,7 +546,7 @@ mod tests {
} }
#[test] #[test]
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
fn test_host_localhost_open_read() { fn test_host_localhost_open_read() {
let host: Localhost = Localhost::new(PathBuf::from("/bin")).ok().unwrap(); let host: Localhost = Localhost::new(PathBuf::from("/bin")).ok().unwrap();
// Create temp file // Create temp file
@@ -555,7 +555,7 @@ mod tests {
} }
#[test] #[test]
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
#[should_panic] #[should_panic]
fn test_host_localhost_open_read_err_no_such_file() { fn test_host_localhost_open_read_err_no_such_file() {
let host: Localhost = Localhost::new(PathBuf::from("/bin")).ok().unwrap(); let host: Localhost = Localhost::new(PathBuf::from("/bin")).ok().unwrap();
@@ -565,7 +565,7 @@ mod tests {
} }
#[test] #[test]
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
fn test_host_localhost_open_read_err_not_accessible() { fn test_host_localhost_open_read_err_not_accessible() {
let host: Localhost = Localhost::new(PathBuf::from("/bin")).ok().unwrap(); let host: Localhost = Localhost::new(PathBuf::from("/bin")).ok().unwrap();
let file: tempfile::NamedTempFile = create_sample_file(); let file: tempfile::NamedTempFile = create_sample_file();
@@ -576,7 +576,7 @@ mod tests {
} }
#[test] #[test]
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
fn test_host_localhost_open_write() { fn test_host_localhost_open_write() {
let host: Localhost = Localhost::new(PathBuf::from("/bin")).ok().unwrap(); let host: Localhost = Localhost::new(PathBuf::from("/bin")).ok().unwrap();
// Create temp file // Create temp file
@@ -585,7 +585,7 @@ mod tests {
} }
#[test] #[test]
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
fn test_host_localhost_open_write_err() { fn test_host_localhost_open_write_err() {
let host: Localhost = Localhost::new(PathBuf::from("/bin")).ok().unwrap(); let host: Localhost = Localhost::new(PathBuf::from("/bin")).ok().unwrap();
let file: tempfile::NamedTempFile = create_sample_file(); let file: tempfile::NamedTempFile = create_sample_file();
@@ -594,7 +594,7 @@ mod tests {
//fs::set_permissions(file.path(), perms)?; //fs::set_permissions(file.path(), perms)?;
assert!(host.open_file_write(file.path()).is_err()); assert!(host.open_file_write(file.path()).is_err());
} }
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
#[test] #[test]
fn test_host_localhost_symlinks() { fn test_host_localhost_symlinks() {
let tmpdir: tempfile::TempDir = tempfile::TempDir::new().unwrap(); let tmpdir: tempfile::TempDir = tempfile::TempDir::new().unwrap();
@@ -643,7 +643,7 @@ mod tests {
} }
#[test] #[test]
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
fn test_host_localhost_mkdir() { fn test_host_localhost_mkdir() {
let tmpdir: tempfile::TempDir = tempfile::TempDir::new().unwrap(); let tmpdir: tempfile::TempDir = tempfile::TempDir::new().unwrap();
let mut host: Localhost = Localhost::new(PathBuf::from(tmpdir.path())).ok().unwrap(); let mut host: Localhost = Localhost::new(PathBuf::from(tmpdir.path())).ok().unwrap();
@@ -661,7 +661,7 @@ mod tests {
} }
#[test] #[test]
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
fn test_host_localhost_remove() { fn test_host_localhost_remove() {
let tmpdir: tempfile::TempDir = tempfile::TempDir::new().unwrap(); let tmpdir: tempfile::TempDir = tempfile::TempDir::new().unwrap();
// Create sample file // Create sample file
@@ -683,7 +683,7 @@ mod tests {
} }
#[test] #[test]
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
fn test_host_localhost_rename() { fn test_host_localhost_rename() {
let tmpdir: tempfile::TempDir = tempfile::TempDir::new().unwrap(); let tmpdir: tempfile::TempDir = tempfile::TempDir::new().unwrap();
// Create sample file // Create sample file
@@ -714,7 +714,7 @@ mod tests {
/// ### create_sample_file /// ### create_sample_file
/// ///
/// Create a sample file /// Create a sample file
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
fn create_sample_file() -> tempfile::NamedTempFile { fn create_sample_file() -> tempfile::NamedTempFile {
// Write // Write
let mut tmpfile: tempfile::NamedTempFile = tempfile::NamedTempFile::new().unwrap(); let mut tmpfile: tempfile::NamedTempFile = tempfile::NamedTempFile::new().unwrap();
@@ -726,7 +726,7 @@ mod tests {
tmpfile tmpfile
} }
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
fn get_filename(entry: &FsEntry) -> String { fn get_filename(entry: &FsEntry) -> String {
match entry { match entry {
FsEntry::Directory(d) => d.name.clone(), FsEntry::Directory(d) => d.name.clone(),
+10 -9
View File
@@ -19,12 +19,13 @@
* *
*/ */
const TERMSCP_VERSION: &'static str = env!("CARGO_PKG_VERSION"); const TERMSCP_VERSION: &str = env!("CARGO_PKG_VERSION");
const TERMSCP_AUTHORS: &'static str = env!("CARGO_PKG_AUTHORS"); const TERMSCP_AUTHORS: &str = env!("CARGO_PKG_AUTHORS");
// Crates // Crates
extern crate getopts; extern crate getopts;
#[macro_use] extern crate lazy_static; #[macro_use]
extern crate lazy_static;
extern crate rpassword; extern crate rpassword;
// External libs // External libs
@@ -50,7 +51,7 @@ use filetransfer::FileTransferProtocol;
/// Print usage /// Print usage
fn print_usage(opts: Options) { fn print_usage(opts: Options) {
let brief = format!("Usage: termscp [options]... [protocol://user@address:port]"); let brief = String::from("Usage: termscp [options]... [protocol://user@address:port]");
print!("{}", opts.usage(&brief)); print!("{}", opts.usage(&brief));
println!("\nPlease, report issues to <https://github.com/ChristianVisintin/TermSCP>"); println!("\nPlease, report issues to <https://github.com/ChristianVisintin/TermSCP>");
} }
@@ -97,7 +98,7 @@ fn main() {
} }
// Match password // Match password
if let Some(passwd) = matches.opt_str("P") { if let Some(passwd) = matches.opt_str("P") {
password = Some(String::from(passwd)); password = Some(passwd);
} }
// Match ticks // Match ticks
if let Some(val) = matches.opt_str("T") { if let Some(val) = matches.opt_str("T") {
@@ -111,7 +112,7 @@ fn main() {
} }
} }
// Check free args // Check free args
let extra_args: Vec<String> = matches.free.clone(); let extra_args: Vec<String> = matches.free;
if let Some(remote) = extra_args.get(0) { if let Some(remote) = extra_args.get(0) {
// Parse address // Parse address
match utils::parse_remote_opt(remote) { match utils::parse_remote_opt(remote) {
@@ -141,10 +142,10 @@ fn main() {
// Ask password if unspecified // Ask password if unspecified
password = match rpassword::read_password_from_tty(Some("Password: ")) { password = match rpassword::read_password_from_tty(Some("Password: ")) {
Ok(p) => { Ok(p) => {
if p.len() > 0 { if p.is_empty() {
Some(p)
} else {
None None
} else {
Some(p)
} }
} }
Err(_) => { Err(_) => {
+14 -20
View File
@@ -85,6 +85,12 @@ pub struct AuthActivity {
redraw: bool, // Should ui actually be redrawned? redraw: bool, // Should ui actually be redrawned?
} }
impl Default for AuthActivity {
fn default() -> Self {
Self::new()
}
}
impl AuthActivity { impl AuthActivity {
/// ### new /// ### new
/// ///
@@ -132,8 +138,7 @@ impl AuthActivity {
/// ///
/// Handler for input event when in textmode /// Handler for input event when in textmode
fn handle_input_event_mode_text(&mut self, ev: &InputEvent) { fn handle_input_event_mode_text(&mut self, ev: &InputEvent) {
match ev { if let InputEvent::Key(key) = ev {
InputEvent::Key(key) => {
match key.code { match key.code {
KeyCode::Esc => { KeyCode::Esc => {
self.quit = true; self.quit = true;
@@ -142,7 +147,7 @@ impl AuthActivity {
// Handle submit // Handle submit
// Check form // Check form
// Check address // Check address
if self.address.len() == 0 { if self.address.is_empty() {
self.popup_message = Some(String::from("Invalid address")); self.popup_message = Some(String::from("Invalid address"));
return; return;
} }
@@ -151,9 +156,8 @@ impl AuthActivity {
match self.port.parse::<usize>() { match self.port.parse::<usize>() {
Ok(val) => { Ok(val) => {
if val > 65535 { if val > 65535 {
self.popup_message = Some(String::from( self.popup_message =
"Specified port must be in range 0-65535", Some(String::from("Specified port must be in range 0-65535"));
));
return; return;
} }
} }
@@ -254,8 +258,6 @@ impl AuthActivity {
_ => { /* Nothing to do */ } _ => { /* Nothing to do */ }
} }
} }
_ => { /* Nothing to do */ }
}
} }
/// ### handle_input_event_mode_text /// ### handle_input_event_mode_text
@@ -263,16 +265,10 @@ impl AuthActivity {
/// Handler for input event when in popup mode /// Handler for input event when in popup mode
fn handle_input_event_mode_popup(&mut self, ev: &InputEvent) { fn handle_input_event_mode_popup(&mut self, ev: &InputEvent) {
// Only enter should be allowed here // Only enter should be allowed here
match ev { if let InputEvent::Key(key) = ev {
InputEvent::Key(key) => { if let KeyCode::Enter = key.code {
match key.code {
KeyCode::Enter => {
self.popup_message = None; // Hide popup self.popup_message = None; // Hide popup
} }
_ => { /* Nothing to do */ }
}
}
_ => { /* Nothing to do */ }
} }
} }
@@ -452,7 +448,7 @@ impl Activity for AuthActivity {
} }
// Start catching Input Events // Start catching Input Events
if let Ok(input_events) = self.context.as_ref().unwrap().input_hnd.fetch_events() { if let Ok(input_events) = self.context.as_ref().unwrap().input_hnd.fetch_events() {
if input_events.len() > 0 { if !input_events.is_empty() {
self.redraw = true; // Set redraw to true if there is at least one event self.redraw = true; // Set redraw to true if there is at least one event
} }
// Iterate over input events // Iterate over input events
@@ -533,9 +529,7 @@ impl Activity for AuthActivity {
fn on_destroy(&mut self) -> Option<Context> { fn on_destroy(&mut self) -> Option<Context> {
// Disable raw mode // Disable raw mode
let _ = disable_raw_mode(); let _ = disable_raw_mode();
if self.context.is_none() { self.context.as_ref()?;
return None;
}
// Clear terminal and return // Clear terminal and return
match self.context.take() { match self.context.take() {
Some(mut ctx) => { Some(mut ctx) => {
@@ -69,8 +69,7 @@ impl FileTransferActivity {
/// Input event handler for explorer mode when localhost tab is selected /// Input event handler for explorer mode when localhost tab is selected
pub(super) fn handle_input_event_mode_explorer_tab_local(&mut self, ev: &InputEvent) { pub(super) fn handle_input_event_mode_explorer_tab_local(&mut self, ev: &InputEvent) {
// Match events // Match events
match ev { if let InputEvent::Key(key) = ev {
InputEvent::Key(key) => {
match key.code { match key.code {
KeyCode::Esc => { KeyCode::Esc => {
// Handle quit event // Handle quit event
@@ -94,7 +93,7 @@ impl FileTransferActivity {
KeyCode::PageUp => { KeyCode::PageUp => {
// Move index up (fast) // Move index up (fast)
if self.local.index > 8 { if self.local.index > 8 {
self.local.index = self.local.index - 8; // Decrease by `8` if possible self.local.index -= 8; // Decrease by `8` if possible
} else { } else {
self.local.index = 0; // Set to 0 otherwise self.local.index = 0; // Set to 0 otherwise
} }
@@ -105,7 +104,7 @@ impl FileTransferActivity {
// If overflows, set to size // If overflows, set to size
self.local.index = self.local.files.len() - 1; self.local.index = self.local.files.len() - 1;
} else { } else {
self.local.index = self.local.index + 8; // Increase by `8` self.local.index += 8; // Increase by `8`
} }
} }
KeyCode::Enter => { KeyCode::Enter => {
@@ -147,8 +146,7 @@ impl FileTransferActivity {
) )
.as_ref(), .as_ref(),
); );
self.input_mode = self.input_mode = InputMode::Popup(PopupType::Alert(
InputMode::Popup(PopupType::Alert(
Color::Red, Color::Red,
format!( format!(
"Failed to stat file \"{}\": {}", "Failed to stat file \"{}\": {}",
@@ -243,8 +241,7 @@ impl FileTransferActivity {
Err(err) => { Err(err) => {
self.log( self.log(
LogLevel::Error, LogLevel::Error,
format!("Could not get current remote path: {}", err) format!("Could not get current remote path: {}", err).as_ref(),
.as_ref(),
); );
self.input_mode = InputMode::Popup(PopupType::Alert( self.input_mode = InputMode::Popup(PopupType::Alert(
Color::Red, Color::Red,
@@ -266,8 +263,6 @@ impl FileTransferActivity {
_ => { /* Nothing to do */ } _ => { /* Nothing to do */ }
} }
} }
_ => { /* Nothing to do */ }
}
} }
/// ### handle_input_event_mode_explorer_tab_local /// ### handle_input_event_mode_explorer_tab_local
@@ -275,8 +270,7 @@ impl FileTransferActivity {
/// Input event handler for explorer mode when remote tab is selected /// Input event handler for explorer mode when remote tab is selected
pub(super) fn handle_input_event_mode_explorer_tab_remote(&mut self, ev: &InputEvent) { pub(super) fn handle_input_event_mode_explorer_tab_remote(&mut self, ev: &InputEvent) {
// Match events // Match events
match ev { if let InputEvent::Key(key) = ev {
InputEvent::Key(key) => {
match key.code { match key.code {
KeyCode::Esc => { KeyCode::Esc => {
// Handle quit event // Handle quit event
@@ -300,7 +294,7 @@ impl FileTransferActivity {
KeyCode::PageUp => { KeyCode::PageUp => {
// Move index up (fast) // Move index up (fast)
if self.remote.index > 8 { if self.remote.index > 8 {
self.remote.index = self.remote.index - 8; // Decrease by `8` if possible self.remote.index -= 8; // Decrease by `8` if possible
} else { } else {
self.remote.index = 0; // Set to 0 otherwise self.remote.index = 0; // Set to 0 otherwise
} }
@@ -311,7 +305,7 @@ impl FileTransferActivity {
// If overflows, set to size // If overflows, set to size
self.remote.index = self.remote.files.len() - 1; self.remote.index = self.remote.files.len() - 1;
} else { } else {
self.remote.index = self.remote.index + 8; // Increase by `8` self.remote.index += 8; // Increase by `8`
} }
} }
KeyCode::Enter => { KeyCode::Enter => {
@@ -347,8 +341,7 @@ impl FileTransferActivity {
) )
.as_ref(), .as_ref(),
); );
self.input_mode = self.input_mode = InputMode::Popup(PopupType::Alert(
InputMode::Popup(PopupType::Alert(
Color::Red, Color::Red,
format!( format!(
"Failed to stat file \"{}\": {}", "Failed to stat file \"{}\": {}",
@@ -463,8 +456,6 @@ impl FileTransferActivity {
_ => { /* Nothing to do */ } _ => { /* Nothing to do */ }
} }
} }
_ => { /* Nothing to do */ }
}
} }
/// ### handle_input_event_mode_explorer_log /// ### handle_input_event_mode_explorer_log
@@ -473,8 +464,7 @@ impl FileTransferActivity {
pub(super) fn handle_input_event_mode_explorer_log(&mut self, ev: &InputEvent) { pub(super) fn handle_input_event_mode_explorer_log(&mut self, ev: &InputEvent) {
// Match event // Match event
let records_block: usize = 16; let records_block: usize = 16;
match ev { if let InputEvent::Key(key) = ev {
InputEvent::Key(key) => {
match key.code { match key.code {
KeyCode::Esc => { KeyCode::Esc => {
// Handle quit event // Handle quit event
@@ -486,21 +476,21 @@ impl FileTransferActivity {
// NOTE: Twisted logic // NOTE: Twisted logic
// Decrease log index // Decrease log index
if self.log_index > 0 { if self.log_index > 0 {
self.log_index = self.log_index - 1; self.log_index -= 1;
} }
} }
KeyCode::Up => { KeyCode::Up => {
// NOTE: Twisted logic // NOTE: Twisted logic
// Increase log index // Increase log index
if self.log_index + 1 < self.log_records.len() { if self.log_index + 1 < self.log_records.len() {
self.log_index = self.log_index + 1; self.log_index += 1;
} }
} }
KeyCode::PageDown => { KeyCode::PageDown => {
// NOTE: Twisted logic // NOTE: Twisted logic
// Fast decreasing of log index // Fast decreasing of log index
if self.log_index >= records_block { if self.log_index >= records_block {
self.log_index = self.log_index - records_block; // Decrease by `records_block` if possible self.log_index -= records_block; // Decrease by `records_block` if possible
} else { } else {
self.log_index = 0; // Set to 0 otherwise self.log_index = 0; // Set to 0 otherwise
} }
@@ -512,7 +502,7 @@ impl FileTransferActivity {
// If overflows, set to size // If overflows, set to size
self.log_index = self.log_records.len() - 1; self.log_index = self.log_records.len() - 1;
} else { } else {
self.log_index = self.log_index + records_block; // Increase by `records_block` self.log_index += records_block; // Increase by `records_block`
} }
} }
KeyCode::Char(ch) => match ch { KeyCode::Char(ch) => match ch {
@@ -525,8 +515,6 @@ impl FileTransferActivity {
_ => { /* Nothing to do */ } _ => { /* Nothing to do */ }
} }
} }
_ => { /* Nothing to do */ }
}
} }
/// ### handle_input_event_mode_explorer /// ### handle_input_event_mode_explorer
@@ -552,17 +540,11 @@ impl FileTransferActivity {
/// Input event handler for popup alert /// Input event handler for popup alert
pub(super) fn handle_input_event_mode_popup_alert(&mut self, ev: &InputEvent) { pub(super) fn handle_input_event_mode_popup_alert(&mut self, ev: &InputEvent) {
// If enter, close popup // If enter, close popup
match ev { if let InputEvent::Key(key) = ev {
InputEvent::Key(key) => { if let KeyCode::Enter = key.code {
match key.code {
KeyCode::Enter => {
// Set input mode back to explorer // Set input mode back to explorer
self.input_mode = InputMode::Explorer; self.input_mode = InputMode::Explorer;
} }
_ => { /* Nothing to do */ }
}
}
_ => { /* Nothing to do */ }
} }
} }
@@ -571,8 +553,7 @@ impl FileTransferActivity {
/// Input event handler for popup fileinfo /// Input event handler for popup fileinfo
pub(super) fn handle_input_event_mode_popup_fileinfo(&mut self, ev: &InputEvent) { pub(super) fn handle_input_event_mode_popup_fileinfo(&mut self, ev: &InputEvent) {
// If enter, close popup // If enter, close popup
match ev { if let InputEvent::Key(key) = ev {
InputEvent::Key(key) => {
match key.code { match key.code {
KeyCode::Enter | KeyCode::Esc => { KeyCode::Enter | KeyCode::Esc => {
// Set input mode back to explorer // Set input mode back to explorer
@@ -581,8 +562,6 @@ impl FileTransferActivity {
_ => { /* Nothing to do */ } _ => { /* Nothing to do */ }
} }
} }
_ => { /* Nothing to do */ }
}
} }
/// ### handle_input_event_mode_popup_help /// ### handle_input_event_mode_popup_help
@@ -590,8 +569,7 @@ impl FileTransferActivity {
/// Input event handler for popup help /// Input event handler for popup help
pub(super) fn handle_input_event_mode_popup_help(&mut self, ev: &InputEvent) { pub(super) fn handle_input_event_mode_popup_help(&mut self, ev: &InputEvent) {
// If enter, close popup // If enter, close popup
match ev { if let InputEvent::Key(key) = ev {
InputEvent::Key(key) => {
match key.code { match key.code {
KeyCode::Enter | KeyCode::Esc => { KeyCode::Enter | KeyCode::Esc => {
// Set input mode back to explorer // Set input mode back to explorer
@@ -600,8 +578,6 @@ impl FileTransferActivity {
_ => { /* Nothing to do */ } _ => { /* Nothing to do */ }
} }
} }
_ => { /* Nothing to do */ }
}
} }
/// ### handle_input_event_mode_popup_fatal /// ### handle_input_event_mode_popup_fatal
@@ -609,17 +585,11 @@ impl FileTransferActivity {
/// Input event handler for popup alert /// Input event handler for popup alert
pub(super) fn handle_input_event_mode_popup_fatal(&mut self, ev: &InputEvent) { pub(super) fn handle_input_event_mode_popup_fatal(&mut self, ev: &InputEvent) {
// If enter, close popup // If enter, close popup
match ev { if let InputEvent::Key(key) = ev {
InputEvent::Key(key) => { if let KeyCode::Enter = key.code {
match key.code {
KeyCode::Enter => {
// Set quit to true; since a fatal error happened // Set quit to true; since a fatal error happened
self.disconnect(); self.disconnect();
} }
_ => { /* Nothing to do */ }
}
}
_ => { /* Nothing to do */ }
} }
} }
@@ -632,8 +602,7 @@ impl FileTransferActivity {
cb: OnInputSubmitCallback, cb: OnInputSubmitCallback,
) { ) {
// If enter, close popup, otherwise push chars to input // If enter, close popup, otherwise push chars to input
match ev { if let InputEvent::Key(key) = ev {
InputEvent::Key(key) => {
match key.code { match key.code {
KeyCode::Esc => { KeyCode::Esc => {
// Abort input // Abort input
@@ -659,28 +628,20 @@ impl FileTransferActivity {
_ => { /* Nothing to do */ } _ => { /* Nothing to do */ }
} }
} }
_ => { /* Nothing to do */ }
}
} }
/// ### handle_input_event_mode_explorer_alert /// ### handle_input_event_mode_explorer_alert
/// ///
/// Input event handler for popup alert /// Input event handler for popup alert
pub(super) fn handle_input_event_mode_popup_progress(&mut self, ev: &InputEvent) { pub(super) fn handle_input_event_mode_popup_progress(&mut self, _ev: &InputEvent) {
// There's nothing you can do here I guess... maybe ctrl+c in the future idk // There's nothing you can do here I guess... maybe ctrl+c in the future idk
match ev {
_ => { /* Nothing to do */ }
}
} }
/// ### handle_input_event_mode_explorer_alert /// ### handle_input_event_mode_explorer_alert
/// ///
/// Input event handler for popup alert /// Input event handler for popup alert
pub(super) fn handle_input_event_mode_popup_wait(&mut self, ev: &InputEvent) { pub(super) fn handle_input_event_mode_popup_wait(&mut self, _ev: &InputEvent) {
// There's nothing you can do here I guess... maybe ctrl+c in the future idk // There's nothing you can do here I guess... maybe ctrl+c in the future idk
match ev {
_ => { /* Nothing to do */ }
}
} }
/// ### handle_input_event_mode_explorer_alert /// ### handle_input_event_mode_explorer_alert
@@ -693,8 +654,7 @@ impl FileTransferActivity {
no_cb: DialogCallback, no_cb: DialogCallback,
) { ) {
// If enter, close popup, otherwise move dialog option // If enter, close popup, otherwise move dialog option
match ev { if let InputEvent::Key(key) = ev {
InputEvent::Key(key) => {
match key.code { match key.code {
KeyCode::Enter => { KeyCode::Enter => {
// @! Set input mode to Explorer BEFORE CALLBACKS!!! Callback can then overwrite this, clever uh? // @! Set input mode to Explorer BEFORE CALLBACKS!!! Callback can then overwrite this, clever uh?
@@ -712,7 +672,5 @@ impl FileTransferActivity {
_ => { /* Nothing to do */ } _ => { /* Nothing to do */ }
} }
} }
_ => { /* Nothing to do */ }
}
} }
} }
@@ -21,7 +21,7 @@
extern crate bytesize; extern crate bytesize;
extern crate hostname; extern crate hostname;
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
extern crate users; extern crate users;
use super::{ use super::{
@@ -39,7 +39,7 @@ use tui::{
widgets::{Block, Borders, Clear, Gauge, List, ListItem, ListState, Paragraph, Tabs}, widgets::{Block, Borders, Clear, Gauge, List, ListItem, ListState, Paragraph, Tabs},
}; };
use unicode_width::UnicodeWidthStr; use unicode_width::UnicodeWidthStr;
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
use users::{get_group_by_gid, get_user_by_uid}; use users::{get_group_by_gid, get_user_by_uid};
impl FileTransferActivity { impl FileTransferActivity {
@@ -115,7 +115,7 @@ impl FileTransferActivity {
f.render_widget(Clear, popup_area); //this clears out the background f.render_widget(Clear, popup_area); //this clears out the background
match popup { match popup {
PopupType::Alert(color, txt) => f.render_widget( PopupType::Alert(color, txt) => f.render_widget(
self.draw_popup_alert(color.clone(), txt.clone(), popup_area.width), self.draw_popup_alert(*color, txt.clone(), popup_area.width),
popup_area, popup_area,
), ),
PopupType::Fatal(txt) => f.render_widget( PopupType::Fatal(txt) => f.render_widget(
@@ -511,7 +511,7 @@ impl FileTransferActivity {
), ),
]))); ])));
// User // User
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
let username: String = match dir.user { let username: String = match dir.user {
Some(uid) => match get_user_by_uid(uid) { Some(uid) => match get_user_by_uid(uid) {
Some(user) => user.name().to_string_lossy().to_string(), Some(user) => user.name().to_string_lossy().to_string(),
@@ -531,7 +531,7 @@ impl FileTransferActivity {
), ),
]))); ])));
// Group // Group
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
let group: String = match dir.group { let group: String = match dir.group {
Some(gid) => match get_group_by_gid(gid) { Some(gid) => match get_group_by_gid(gid) {
Some(group) => group.name().to_string_lossy().to_string(), Some(group) => group.name().to_string_lossy().to_string(),
@@ -608,7 +608,7 @@ impl FileTransferActivity {
), ),
]))); ])));
// User // User
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
let username: String = match file.user { let username: String = match file.user {
Some(uid) => match get_user_by_uid(uid) { Some(uid) => match get_user_by_uid(uid) {
Some(user) => user.name().to_string_lossy().to_string(), Some(user) => user.name().to_string_lossy().to_string(),
@@ -628,7 +628,7 @@ impl FileTransferActivity {
), ),
]))); ])));
// Group // Group
#[cfg(any(unix, macos, linux))] #[cfg(any(target_os = "unix", target_os = "macos", target_os = "linux"))]
let group: String = match file.group { let group: String = match file.group {
Some(gid) => match get_group_by_gid(gid) { Some(gid) => match get_group_by_gid(gid) {
Some(group) => group.name().to_string_lossy().to_string(), Some(group) => group.name().to_string_lossy().to_string(),
@@ -199,7 +199,7 @@ impl LogRecord {
pub fn new(level: LogLevel, msg: &str) -> LogRecord { pub fn new(level: LogLevel, msg: &str) -> LogRecord {
LogRecord { LogRecord {
time: Local::now(), time: Local::now(),
level: level, level,
msg: String::from(msg), msg: String::from(msg),
} }
} }
@@ -243,7 +243,7 @@ impl FileTransferActivity {
FileTransferProtocol::Ftp(ftps) => Box::new(FtpFileTransfer::new(ftps)), FileTransferProtocol::Ftp(ftps) => Box::new(FtpFileTransfer::new(ftps)),
FileTransferProtocol::Scp => Box::new(ScpFileTransfer::new()), FileTransferProtocol::Scp => Box::new(ScpFileTransfer::new()),
}, },
params: params, params,
local: FileExplorer::new(), local: FileExplorer::new(),
remote: FileExplorer::new(), remote: FileExplorer::new(),
tab: FileExplorerTab::Local, tab: FileExplorerTab::Local,
@@ -292,10 +292,7 @@ impl Activity for FileTransferActivity {
if self.context.is_none() { if self.context.is_none() {
return; return;
} }
let is_explorer_mode: bool = match self.input_mode { let is_explorer_mode: bool = matches!(self.input_mode, InputMode::Explorer);
InputMode::Explorer => true,
_ => false,
};
// Check if connected // Check if connected
if !self.client.is_connected() && is_explorer_mode { if !self.client.is_connected() && is_explorer_mode {
// Set init state to connecting popup // Set init state to connecting popup
@@ -385,7 +385,7 @@ impl FileTransferActivity {
// Get local file // Get local file
let mut local_file_path: PathBuf = PathBuf::from(local_path); let mut local_file_path: PathBuf = PathBuf::from(local_path);
let local_file_name: String = match dst_name { let local_file_name: String = match dst_name {
Some(n) => n.clone(), Some(n) => n,
None => file.name.clone(), None => file.name.clone(),
}; };
local_file_path.push(local_file_name.as_str()); local_file_path.push(local_file_name.as_str());
+1 -2
View File
@@ -57,7 +57,7 @@ impl Context {
let mut stdout = stdout(); let mut stdout = stdout();
assert!(execute!(stdout, EnterAlternateScreen).is_ok()); assert!(execute!(stdout, EnterAlternateScreen).is_ok());
Context { Context {
local: local, local,
input_hnd: InputHandler::new(), input_hnd: InputHandler::new(),
terminal: Terminal::new(CrosstermBackend::new(stdout)).unwrap() terminal: Terminal::new(CrosstermBackend::new(stdout)).unwrap()
} }
@@ -72,7 +72,6 @@ impl Drop for Context {
LeaveAlternateScreen, LeaveAlternateScreen,
DisableMouseCapture DisableMouseCapture
); );
drop(self);
} }
} }
+4 -4
View File
@@ -53,9 +53,9 @@ use std::time::{Duration, SystemTime};
/// - ... /// - ...
/// ///
pub fn parse_remote_opt( pub fn parse_remote_opt(
remote: &String, remote: &str,
) -> Result<(String, u16, FileTransferProtocol, Option<String>), String> { ) -> Result<(String, u16, FileTransferProtocol, Option<String>), String> {
let mut wrkstr: String = remote.clone(); let mut wrkstr: String = remote.to_string();
let address: String; let address: String;
let mut port: u16 = 22; let mut port: u16 = 22;
let mut protocol: FileTransferProtocol = FileTransferProtocol::Sftp; let mut protocol: FileTransferProtocol = FileTransferProtocol::Sftp;
@@ -104,7 +104,7 @@ pub fn parse_remote_opt(
username = Some(whoami::username()); username = Some(whoami::username());
} }
// Split wrkstring by '@' // Split wrkstring by '@'
let tokens: Vec<&str> = wrkstr.split("@").collect(); let tokens: Vec<&str> = wrkstr.split('@').collect();
match tokens.len() { match tokens.len() {
1 => {} 1 => {}
2 => { 2 => {
@@ -116,7 +116,7 @@ pub fn parse_remote_opt(
_ => return Err(String::from("Bad syntax")), // Too many tokens... _ => return Err(String::from("Bad syntax")), // Too many tokens...
} }
// Split wrkstring by ':' // Split wrkstring by ':'
let tokens: Vec<&str> = wrkstr.split(":").collect(); let tokens: Vec<&str> = wrkstr.split(':').collect();
match tokens.len() { match tokens.len() {
1 => { 1 => {
// Address is wrkstr // Address is wrkstr