uptime: Add -s/--since option to output only when the system came online

This also matches Linux and the BSDs.
This commit is contained in:
Sam Atkins 2024-01-24 12:46:13 +00:00 committed by Andreas Kling
parent 8faeb13036
commit 7bcb560060
2 changed files with 13 additions and 1 deletions

View file

@ -16,6 +16,7 @@ This information includes when the system came online and how long it has been u
## Options
* `-p`, `--pretty`: Output only the uptime, in human-readable format.
* `-s`, `--since`: Output only the datetime when the system came online.
## Examples
@ -28,3 +29,8 @@ $ uptime
$ uptime -p
Up 2 minutes, 20 seconds
```
```sh
$ uptime -s
2024-01-24 06:23:27
```

View file

@ -18,9 +18,11 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
TRY(Core::System::pledge("stdio rpath"));
bool pretty_output = false;
bool output_since = false;
Core::ArgsParser args_parser;
args_parser.add_option(pretty_output, "Output only the uptime, in human-readable format", "pretty", 'p');
args_parser.add_option(output_since, "Show when the system is up since, in yyyy-mm-dd HH:MM:SS format", "since", 's');
args_parser.parse(arguments);
auto file = TRY(Core::File::open("/sys/kernel/uptime"sv, Core::File::OpenMode::Read));
@ -34,7 +36,11 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
return Error::from_string_literal("Couldn't convert to number");
auto seconds = maybe_seconds.release_value();
if (pretty_output) {
if (output_since) {
auto since_timestamp = Core::DateTime::now().timestamp() - seconds;
auto since_time = TRY(Core::DateTime::from_timestamp(since_timestamp).to_string());
outln("{}", since_time);
} else if (pretty_output) {
outln("Up {}", human_readable_time(seconds));
} else {
auto current_time = TRY(Core::DateTime::now().to_string());