nushell/src/plugins/sys.rs

332 lines
11 KiB
Rust
Raw Normal View History

2019-08-28 17:53:59 +02:00
use std::ffi::OsStr;
use futures::executor::block_on;
use futures::stream::StreamExt;
use heim::units::{frequency, information, thermodynamic_temperature, time};
use heim::{disk, host, memory, net, sensors};
use nu::{
2019-08-09 06:51:21 +02:00
serve_plugin, CallInfo, Plugin, Primitive, ReturnSuccess, ReturnValue, ShellError, Signature,
2019-08-27 18:26:14 +02:00
Tag, Tagged, TaggedDictBuilder, Value,
};
struct Sys;
impl Sys {
fn new() -> Sys {
Sys
}
}
async fn cpu(tag: Tag) -> Option<Tagged<Value>> {
match futures::future::try_join(heim::cpu::logical_count(), heim::cpu::frequency()).await {
2019-08-28 17:53:59 +02:00
Ok((num_cpu, cpu_speed)) => {
let mut cpu_idx = TaggedDictBuilder::with_capacity(tag, 4);
cpu_idx.insert("cores", Primitive::number(num_cpu));
2019-08-28 17:53:59 +02:00
let current_speed =
(cpu_speed.current().get::<frequency::hertz>() as f64 / 1_000_000_000.0 * 100.0)
.round()
/ 100.0;
cpu_idx.insert("current ghz", Primitive::number(current_speed));
2019-08-28 17:53:59 +02:00
if let Some(min_speed) = cpu_speed.min() {
let min_speed =
(min_speed.get::<frequency::hertz>() as f64 / 1_000_000_000.0 * 100.0).round()
/ 100.0;
cpu_idx.insert("min ghz", Primitive::number(min_speed));
2019-08-28 17:53:59 +02:00
}
2019-08-11 05:33:26 +02:00
2019-08-28 17:53:59 +02:00
if let Some(max_speed) = cpu_speed.max() {
let max_speed =
(max_speed.get::<frequency::hertz>() as f64 / 1_000_000_000.0 * 100.0).round()
/ 100.0;
cpu_idx.insert("max ghz", Primitive::number(max_speed));
2019-08-28 17:53:59 +02:00
}
Some(cpu_idx.into_tagged_value())
}
2019-08-28 17:53:59 +02:00
Err(_) => None,
2019-07-27 22:09:25 +02:00
}
}
async fn mem(tag: Tag) -> Tagged<Value> {
2019-08-28 17:53:59 +02:00
let mut dict = TaggedDictBuilder::with_capacity(tag, 4);
let (memory_result, swap_result) =
futures::future::join(memory::memory(), memory::swap()).await;
2019-08-28 17:53:59 +02:00
if let Ok(memory) = memory_result {
dict.insert(
"total",
Value::bytes(memory.total().get::<information::byte>()),
);
dict.insert(
"free",
Value::bytes(memory.free().get::<information::byte>()),
);
2019-07-30 03:14:01 +02:00
}
2019-08-28 17:53:59 +02:00
if let Ok(swap) = swap_result {
dict.insert(
"swap total",
Value::bytes(swap.total().get::<information::byte>()),
);
dict.insert(
"swap free",
Value::bytes(swap.free().get::<information::byte>()),
);
2019-07-30 03:14:01 +02:00
}
2019-07-27 22:09:25 +02:00
2019-08-01 03:58:42 +02:00
dict.into_tagged_value()
}
async fn host(tag: Tag) -> Tagged<Value> {
2019-08-28 17:53:59 +02:00
let mut dict = TaggedDictBuilder::with_capacity(tag, 6);
let (platform_result, uptime_result) =
futures::future::join(host::platform(), host::uptime()).await;
2019-07-27 22:09:25 +02:00
// OS
2019-08-28 17:53:59 +02:00
if let Ok(platform) = platform_result {
2019-07-27 22:09:25 +02:00
dict.insert("name", Value::string(platform.system()));
dict.insert("release", Value::string(platform.release()));
dict.insert("hostname", Value::string(platform.hostname()));
dict.insert("arch", Value::string(platform.architecture().as_str()));
}
// Uptime
2019-08-28 17:53:59 +02:00
if let Ok(uptime) = uptime_result {
let mut uptime_dict = TaggedDictBuilder::with_capacity(tag, 4);
2019-07-27 22:09:25 +02:00
2019-08-28 17:53:59 +02:00
let uptime = uptime.get::<time::second>().round() as i64;
2019-07-27 22:09:25 +02:00
let days = uptime / (60 * 60 * 24);
let hours = (uptime - days * 60 * 60 * 24) / (60 * 60);
let minutes = (uptime - days * 60 * 60 * 24 - hours * 60 * 60) / 60;
let seconds = uptime % 60;
uptime_dict.insert("days", Value::int(days));
uptime_dict.insert("hours", Value::int(hours));
uptime_dict.insert("mins", Value::int(minutes));
uptime_dict.insert("secs", Value::int(seconds));
2019-08-28 17:53:59 +02:00
dict.insert_tagged("uptime", uptime_dict);
2019-07-27 22:09:25 +02:00
}
// Users
2019-08-28 17:53:59 +02:00
let mut users = host::users();
2019-07-27 22:09:25 +02:00
let mut user_vec = vec![];
while let Some(user) = users.next().await {
2019-07-30 03:14:01 +02:00
if let Ok(user) = user {
user_vec.push(Tagged::from_item(Value::string(user.username()), tag));
2019-07-30 03:14:01 +02:00
}
2019-07-27 22:09:25 +02:00
}
let user_list = Value::Table(user_vec);
2019-07-27 22:09:25 +02:00
dict.insert("users", user_list);
2019-08-01 03:58:42 +02:00
dict.into_tagged_value()
}
2019-08-11 05:01:09 +02:00
async fn disks(tag: Tag) -> Option<Value> {
let mut output = vec![];
let mut partitions = disk::partitions_physical();
while let Some(part) = partitions.next().await {
2019-07-30 03:14:01 +02:00
if let Ok(part) = part {
2019-08-28 17:53:59 +02:00
let mut dict = TaggedDictBuilder::with_capacity(tag, 6);
2019-07-30 03:14:01 +02:00
dict.insert(
"device",
Value::string(
part.device()
.unwrap_or_else(|| OsStr::new("N/A"))
.to_string_lossy(),
),
);
dict.insert("type", Value::string(part.file_system().as_str()));
dict.insert("mount", Value::string(part.mount_point().to_string_lossy()));
2019-08-28 17:53:59 +02:00
2019-07-30 03:14:01 +02:00
if let Ok(usage) = disk::usage(part.mount_point().to_path_buf()).await {
dict.insert(
"total",
Value::bytes(usage.total().get::<information::byte>()),
);
dict.insert(
"used",
Value::bytes(usage.used().get::<information::byte>()),
);
dict.insert(
"free",
Value::bytes(usage.free().get::<information::byte>()),
);
2019-07-30 03:14:01 +02:00
}
2019-08-28 17:53:59 +02:00
2019-08-01 03:58:42 +02:00
output.push(dict.into_tagged_value());
2019-07-30 03:14:01 +02:00
}
}
2019-08-28 17:53:59 +02:00
if !output.is_empty() {
Some(Value::Table(output))
2019-08-11 05:01:09 +02:00
} else {
None
}
}
async fn battery(tag: Tag) -> Option<Value> {
let mut output = vec![];
if let Ok(manager) = battery::Manager::new() {
if let Ok(batteries) = manager.batteries() {
for battery in batteries {
if let Ok(battery) = battery {
let mut dict = TaggedDictBuilder::new(tag);
if let Some(vendor) = battery.vendor() {
dict.insert("vendor", Value::string(vendor));
}
if let Some(model) = battery.model() {
dict.insert("model", Value::string(model));
}
if let Some(cycles) = battery.cycle_count() {
dict.insert("cycles", Value::int(cycles));
}
if let Some(time_to_full) = battery.time_to_full() {
dict.insert(
"mins to full",
Value::number(time_to_full.get::<battery::units::time::minute>()),
2019-08-11 05:01:09 +02:00
);
}
if let Some(time_to_empty) = battery.time_to_empty() {
dict.insert(
"mins to empty",
Value::number(time_to_empty.get::<battery::units::time::minute>()),
2019-08-11 05:01:09 +02:00
);
}
output.push(dict.into_tagged_value());
}
}
}
}
2019-08-28 17:53:59 +02:00
if !output.is_empty() {
Some(Value::Table(output))
2019-08-11 05:01:09 +02:00
} else {
None
}
}
2019-08-28 17:53:59 +02:00
async fn temp(tag: Tag) -> Option<Value> {
let mut output = vec![];
let mut sensors = sensors::temperatures();
while let Some(sensor) = sensors.next().await {
if let Ok(sensor) = sensor {
let mut dict = TaggedDictBuilder::new(tag);
dict.insert("unit", Value::string(sensor.unit()));
if let Some(label) = sensor.label() {
dict.insert("label", Value::string(label));
}
dict.insert(
"temp",
Value::number(
sensor
.current()
.get::<thermodynamic_temperature::degree_celsius>(),
),
);
2019-08-28 17:53:59 +02:00
if let Some(high) = sensor.high() {
dict.insert(
"high",
Value::number(high.get::<thermodynamic_temperature::degree_celsius>()),
);
2019-08-28 17:53:59 +02:00
}
if let Some(critical) = sensor.critical() {
dict.insert(
"critical",
Value::number(critical.get::<thermodynamic_temperature::degree_celsius>()),
);
2019-08-28 17:53:59 +02:00
}
output.push(dict.into_tagged_value());
}
}
if !output.is_empty() {
Some(Value::Table(output))
2019-08-28 17:53:59 +02:00
} else {
None
}
}
2019-07-28 04:02:42 +02:00
2019-08-11 05:01:09 +02:00
async fn net(tag: Tag) -> Option<Value> {
2019-08-11 00:13:03 +02:00
let mut output = vec![];
let mut io_counters = net::io_counters();
while let Some(nic) = io_counters.next().await {
if let Ok(nic) = nic {
2019-08-28 17:53:59 +02:00
let mut network_idx = TaggedDictBuilder::with_capacity(tag, 3);
2019-08-11 00:13:03 +02:00
network_idx.insert("name", Value::string(nic.interface()));
network_idx.insert(
"sent",
Value::bytes(nic.bytes_sent().get::<information::byte>()),
);
network_idx.insert(
"recv",
Value::bytes(nic.bytes_recv().get::<information::byte>()),
);
2019-08-11 00:13:03 +02:00
output.push(network_idx.into_tagged_value());
}
}
2019-08-28 17:53:59 +02:00
if !output.is_empty() {
Some(Value::Table(output))
2019-08-11 05:01:09 +02:00
} else {
None
}
2019-07-28 04:02:42 +02:00
}
async fn sysinfo(tag: Tag) -> Vec<Tagged<Value>> {
2019-08-28 17:53:59 +02:00
let mut sysinfo = TaggedDictBuilder::with_capacity(tag, 7);
let (host, cpu, disks, memory, temp) =
futures::future::join5(host(tag), cpu(tag), disks(tag), mem(tag), temp(tag)).await;
let (net, battery) = futures::future::join(net(tag), battery(tag)).await;
2019-08-28 17:53:59 +02:00
sysinfo.insert_tagged("host", host);
if let Some(cpu) = cpu {
2019-08-01 03:58:42 +02:00
sysinfo.insert_tagged("cpu", cpu);
2019-07-27 22:09:25 +02:00
}
2019-08-28 17:53:59 +02:00
if let Some(disks) = disks {
2019-08-11 05:01:09 +02:00
sysinfo.insert("disks", disks);
}
2019-08-28 17:53:59 +02:00
sysinfo.insert_tagged("mem", memory);
if let Some(temp) = temp {
sysinfo.insert("temp", temp);
}
if let Some(net) = net {
2019-08-11 05:01:09 +02:00
sysinfo.insert("net", net);
}
2019-08-28 17:53:59 +02:00
if let Some(battery) = battery {
2019-08-11 05:01:09 +02:00
sysinfo.insert("battery", battery);
}
2019-08-01 03:58:42 +02:00
vec![sysinfo.into_tagged_value()]
}
impl Plugin for Sys {
2019-08-09 06:51:21 +02:00
fn config(&mut self) -> Result<Signature, ShellError> {
Ok(Signature::build("sys")
.desc("View information about the current system.")
.filter())
}
Add support for ~ expansion This ended up being a bit of a yak shave. The basic idea in this commit is to expand `~` in paths, but only in paths. The way this is accomplished is by doing the expansion inside of the code that parses literal syntax for `SyntaxType::Path`. As a quick refresher: every command is entitled to expand its arguments in a custom way. While this could in theory be used for general-purpose macros, today the expansion facility is limited to syntactic hints. For example, the syntax `where cpu > 0` expands under the hood to `where { $it.cpu > 0 }`. This happens because the first argument to `where` is defined as a `SyntaxType::Block`, and the parser coerces binary expressions whose left-hand-side looks like a member into a block when the command is expecting one. This is mildly more magical than what most programming languages would do, but we believe that it makes sense to allow commands to fine-tune the syntax because of the domain nushell is in (command-line shells). The syntactic expansions supported by this facility are relatively limited. For example, we don't allow `$it` to become a bare word, simply because the command asks for a string in the relevant position. That would quickly become more confusing than it's worth. This PR adds a new `SyntaxType` rule: `SyntaxType::Path`. When a command declares a parameter as a `SyntaxType::Path`, string literals and bare words passed as an argument to that parameter are processed using the path expansion rules. Right now, that only means that `~` is expanded into the home directory, but additional rules are possible in the future. By restricting this expansion to a syntactic expansion when passed as an argument to a command expecting a path, we avoid making `~` a generally reserved character. This will also allow us to give good tab completion for paths with `~` characters in them when a command is expecting a path. In order to accomplish the above, this commit changes the parsing functions to take a `Context` instead of just a `CommandRegistry`. From the perspective of macro expansion, you can think of the `CommandRegistry` as a dictionary of in-scope macros, and the `Context` as the compile-time state used in expansion. This could gain additional functionality over time as we find more uses for the expansion system.
2019-08-26 21:21:03 +02:00
fn begin_filter(&mut self, callinfo: CallInfo) -> Result<Vec<ReturnValue>, ShellError> {
Ok(block_on(sysinfo(Tag::unknown_origin(callinfo.name_span)))
.into_iter()
2019-08-28 17:53:59 +02:00
.map(ReturnSuccess::value)
.collect())
}
2019-08-01 03:58:42 +02:00
fn filter(&mut self, _: Tagged<Value>) -> Result<Vec<ReturnValue>, ShellError> {
Ok(vec![])
}
}
fn main() {
serve_plugin(&mut Sys::new());
}