-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommands.rs
More file actions
91 lines (78 loc) · 2.23 KB
/
commands.rs
File metadata and controls
91 lines (78 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
use comfy_table::{Table, presets::UTF8_FULL};
use crate::ssh::registry::SSHRegistry;
use crate::ssh::utils::{SSHProtocol, connect_secure_server, copy_ssh_key, remove_ssh_key};
pub fn handle_use(
registry: &SSHRegistry,
id: u32,
sftp: bool,
private_key_path: &str,
) -> Result<(), Box<dyn std::error::Error>> {
let server = registry
.servers()
.iter()
.find(|s| s.id == id)
.ok_or(format!("server with id {} not found", id))?;
connect_secure_server(
&server.host,
&server.user,
if sftp {
SSHProtocol::SFTP
} else {
SSHProtocol::SSH
},
server
.existing_ssh_key
.as_deref()
.unwrap_or(private_key_path),
);
Ok(())
}
pub fn handle_ls(registry: &SSHRegistry) {
let mut table = Table::new();
table.load_preset(UTF8_FULL);
table.set_header(vec!["ID", "Name", "User", "Host"]);
for e in registry.servers() {
table.add_row(vec![
e.id.to_string(),
e.name.clone(),
e.user.clone(),
e.host.clone(),
]);
}
println!("{table}");
}
pub fn handle_add(
registry: &mut SSHRegistry,
user: String,
host: String,
mut name: String,
existing_ssh_key: Option<String>,
public_key_path: Option<&str>,
) -> Result<(), Box<dyn std::error::Error>> {
if name.is_empty() {
name = format!("{}@{}", user, host);
}
let max_id = registry.servers().iter().map(|s| s.id).max().unwrap_or(0);
let id = max_id + 1;
let new_server = crate::ssh::registry::Server {
id: id,
name: name,
user: user,
host: host,
existing_ssh_key: existing_ssh_key,
};
if new_server.existing_ssh_key.is_none() {
copy_ssh_key(&new_server.host, &new_server.user, public_key_path.unwrap());
}
registry.add(&new_server)?;
println!("Added entry with id {}", id);
Ok(())
}
pub fn handle_rm(registry: &mut SSHRegistry, id: u32) -> Result<(), Box<dyn std::error::Error>> {
let server = registry.remove(id)?;
if server.existing_ssh_key.is_none() {
remove_ssh_key(&server.host);
}
println!("Removed entry with id {}", id);
Ok(())
}