@@ -13,7 +13,7 @@ use libc::{sysconf, _SC_CLK_TCK};
1313use std:: { collections:: HashMap , fs, path:: Path , time:: SystemTime } ;
1414use std:: { process, time:: Duration } ;
1515use uucore:: uptime:: {
16- get_formated_uptime , get_formatted_loadavg, get_formatted_nusers, get_formatted_time,
16+ get_formatted_loadavg, get_formatted_nusers, get_formatted_time, get_uptime , UptimeError ,
1717} ;
1818#[ cfg( target_os = "linux" ) ]
1919use uucore:: utmpx:: Utmpx ;
@@ -187,9 +187,35 @@ fn fetch_user_info() -> Result<Vec<UserInfo>, std::io::Error> {
187187 Ok ( user_info_list)
188188}
189189
190+ pub fn format_uptime_procps ( up_secs : i64 ) -> UResult < String > {
191+ if up_secs < 0 {
192+ Err ( UptimeError :: SystemUptime ) ?;
193+ }
194+ let up_days = up_secs / 86400 ;
195+ let up_hours = ( up_secs - ( up_days * 86400 ) ) / 3600 ;
196+ let up_mins = ( up_secs - ( up_days * 86400 ) - ( up_hours * 3600 ) ) / 60 ;
197+ let day_str = match up_days. cmp ( & 1 ) {
198+ std:: cmp:: Ordering :: Equal => format ! ( "{up_days:1} day, " ) ,
199+ std:: cmp:: Ordering :: Greater => format ! ( "{up_days:1} days, " ) ,
200+ _ => String :: new ( ) ,
201+ } ;
202+ let hour_min_str = if up_hours > 0 {
203+ format ! ( "{up_hours:2}:{up_mins:02}" )
204+ } else {
205+ format ! ( "{up_mins} min" )
206+ } ;
207+ Ok ( format ! ( "{}{}" , day_str, hour_min_str) )
208+ }
209+
210+ #[ inline]
211+ pub fn get_formatted_uptime_procps ( ) -> UResult < String > {
212+ let time_str = format_uptime_procps ( get_uptime ( None ) ?) ?;
213+ Ok ( format ! ( "up {}" , time_str) )
214+ }
215+
190216fn print_uptime ( ) {
191217 print ! ( " {} " , get_formatted_time( ) ) ;
192- if let Ok ( uptime) = get_formated_uptime ( None ) {
218+ if let Ok ( uptime) = get_formatted_uptime_procps ( ) {
193219 print ! ( "{}, " , uptime) ;
194220 } else {
195221 print ! ( "up ???? days ??:??, " ) ;
@@ -329,7 +355,7 @@ pub fn uu_app() -> Command {
329355mod tests {
330356 use crate :: {
331357 fetch_cmdline, fetch_pcpu_time, fetch_terminal_number, format_time, format_time_elapsed,
332- get_clock_tick,
358+ format_uptime_procps , get_clock_tick,
333359 } ;
334360 use std:: { fs, path:: Path , process, time:: Duration } ;
335361
@@ -400,4 +426,26 @@ mod tests {
400426 ( utime + stime) / get_clock_tick( ) as f64
401427 )
402428 }
429+
430+ #[ test]
431+ fn test_format_uptime ( ) {
432+ let test_times = [
433+ ( 1 , "0 min" ) ,
434+ ( 10 , "0 min" ) ,
435+ ( 60 , "1 min" ) ,
436+ ( 100 , "1 min" ) ,
437+ ( 200 , "3 min" ) ,
438+ ( 3600 , " 1:00" ) ,
439+ ( 5000 , " 1:23" ) ,
440+ ( 3600 * 24 , "1 day, 0 min" ) ,
441+ ( 3600 * 24 + 60 , "1 day, 1 min" ) ,
442+ ( 3600 * 24 + 3600 , "1 day, 1:00" ) ,
443+ ] ;
444+
445+ test_times. iter ( ) . for_each ( |up_secs| {
446+ let result = format_uptime_procps ( up_secs. 0 ) . unwrap ( ) ;
447+
448+ assert_eq ! ( result, up_secs. 1 ) ;
449+ } )
450+ }
403451}
0 commit comments