From 5314430437d117d2e041b87cc568702c66f8702a Mon Sep 17 00:00:00 2001 From: Eelco Dolstra Date: Fri, 10 May 2024 16:49:40 +0200 Subject: [PATCH] Move printSize() into libutil Also always include the unit (i.e. "MiB" instead of "M"). --- src/libutil/util.cc | 15 +++++++++++++++ src/libutil/util.hh | 6 ++++++ src/nix/path-info.cc | 17 +++-------------- src/nix/path-info.md | 4 ++-- 4 files changed, 26 insertions(+), 16 deletions(-) diff --git a/src/libutil/util.cc b/src/libutil/util.cc index 103ce4232..f893fc12d 100644 --- a/src/libutil/util.cc +++ b/src/libutil/util.cc @@ -112,6 +112,21 @@ std::string rewriteStrings(std::string s, const StringMap & rewrites) } +std::string renderSize(uint64_t value) +{ + static const std::array prefixes{{ + 'K', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y' + }}; + size_t power = 0; + double res = value; + while (res > 1024 && power < prefixes.size()) { + ++power; + res /= 1024; + } + return fmt("%6.1f %ciB", power == 0 ? res / 1024 : res, prefixes.at(power)); +} + + bool hasPrefix(std::string_view s, std::string_view prefix) { return s.compare(0, prefix.size(), prefix) == 0; diff --git a/src/libutil/util.hh b/src/libutil/util.hh index 8b049875a..01e42ce57 100644 --- a/src/libutil/util.hh +++ b/src/libutil/util.hh @@ -137,6 +137,12 @@ N string2IntWithUnitPrefix(std::string_view s) throw UsageError("'%s' is not an integer", s); } +/** + * Pretty-print a byte value, e.g. 12433615056 is rendered as `11.6 + * GiB`. + */ +std::string renderSize(uint64_t value); + /** * Parse a string into a float. */ diff --git a/src/nix/path-info.cc b/src/nix/path-info.cc index 921b25d7f..a1a2c40f4 100644 --- a/src/nix/path-info.cc +++ b/src/nix/path-info.cc @@ -139,21 +139,10 @@ struct CmdPathInfo : StorePathsCommand, MixJSON void printSize(uint64_t value) { - if (!humanReadable) { + if (humanReadable) + std::cout << fmt("\t%s", renderSize(value)); + else std::cout << fmt("\t%11d", value); - return; - } - - static const std::array idents{{ - ' ', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y' - }}; - size_t power = 0; - double res = value; - while (res > 1024 && power < idents.size()) { - ++power; - res /= 1024; - } - std::cout << fmt("\t%6.1f%c", res, idents.at(power)); } void run(ref store, StorePaths && storePaths) override diff --git a/src/nix/path-info.md b/src/nix/path-info.md index 789984559..2e39225b8 100644 --- a/src/nix/path-info.md +++ b/src/nix/path-info.md @@ -26,8 +26,8 @@ R""( ```console # nix path-info --recursive --size --closure-size --human-readable nixpkgs#rustc - /nix/store/01rrgsg5zk3cds0xgdsq40zpk6g51dz9-ncurses-6.2-dev 386.7K 69.1M - /nix/store/0q783wnvixpqz6dxjp16nw296avgczam-libpfm-4.11.0 5.9M 37.4M + /nix/store/01rrgsg5zk3cds0xgdsq40zpk6g51dz9-ncurses-6.2-dev 386.7 KiB 69.1 MiB + /nix/store/0q783wnvixpqz6dxjp16nw296avgczam-libpfm-4.11.0 5.9 MiB 37.4 MiB … ```