Skip to content

Commit c564ef0

Browse files
committed
w: add uptime header
1 parent 1f72da9 commit c564ef0

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

src/uu/w/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ keywords = ["acl", "uutils", "cross-platform", "cli", "utility"]
1212
categories = ["command-line-utilities"]
1313

1414
[dependencies]
15-
uucore = { workspace = true, features = ["utmpx"] }
15+
uucore = { workspace = true, features = ["utmpx", "uptime"] }
1616
clap = { workspace = true }
1717
chrono = { workspace = true, default-features = false, features = [
1818
"clock",

src/uu/w/src/w.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@ use libc::{sysconf, _SC_CLK_TCK};
1212
#[cfg(target_os = "linux")]
1313
use std::{collections::HashMap, fs, path::Path, time::SystemTime};
1414
use std::{process, time::Duration};
15+
use uucore::uptime::{
16+
get_formated_uptime, get_formatted_loadavg, get_formatted_nusers, get_formatted_time,
17+
};
1518
#[cfg(target_os = "linux")]
1619
use uucore::utmpx::Utmpx;
1720
use uucore::{error::UResult, format_usage, help_about, help_usage};
@@ -184,6 +187,23 @@ fn fetch_user_info() -> Result<Vec<UserInfo>, std::io::Error> {
184187
Ok(user_info_list)
185188
}
186189

190+
fn print_uptime() {
191+
print!(" {} ", get_formatted_time());
192+
match get_formated_uptime(None) {
193+
Ok(uptime) => {
194+
print!("{}, ", uptime);
195+
}
196+
Err(_) => {
197+
print!("up ???? days ??:??, ");
198+
}
199+
}
200+
print!(" {}", get_formatted_nusers());
201+
if let Ok(loadavg) = get_formatted_loadavg() {
202+
print!(", {}", loadavg);
203+
}
204+
println!();
205+
}
206+
187207
#[cfg(any(target_os = "macos", target_os = "windows"))]
188208
fn fetch_user_info() -> Result<Vec<UserInfo>, std::io::Error> {
189209
Ok(Vec::new())
@@ -200,6 +220,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
200220
match fetch_user_info() {
201221
Ok(user_info) => {
202222
if !no_header {
223+
print_uptime();
203224
if short {
204225
println!("{:<9}{:<9}{:<7}{:<}", "USER", "TTY", "IDLE", "WHAT");
205226
} else {

tests/by-util/test_w.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,10 @@ fn test_no_header() {
2626

2727
let result = cmd.stdout_str();
2828

29+
assert!(match result.lines().next() {
30+
None => true,
31+
Some(line) => !line.contains("user") && !line.contains("load average"),
32+
});
2933
assert!(!result.contains("USER TTY LOGIN@ IDLE JCPU PCPU WHAT"));
3034
}
3135
}

0 commit comments

Comments
 (0)