From 87b32bab05ff91981c8847d66cd5502feb44f3b5 Mon Sep 17 00:00:00 2001 From: John Ericson Date: Sat, 28 Mar 2020 23:22:10 +0000 Subject: Use `enum struct` and drop prefixes This does a few enums; the rest will be gotten in subsequent commits. --- src/libutil/args.cc | 2 +- src/libutil/args.hh | 2 +- src/libutil/compression.cc | 2 +- src/libutil/hash.cc | 70 ++++++++++++++++++------------------ src/libutil/hash.hh | 33 +++++++++++------ src/libutil/logging.cc | 18 +++++----- src/libutil/logging.hh | 88 +++++++++++++++++++++++----------------------- src/libutil/util.cc | 4 +-- src/libutil/util.hh | 2 +- 9 files changed, 116 insertions(+), 105 deletions(-) (limited to 'src/libutil') diff --git a/src/libutil/args.cc b/src/libutil/args.cc index ba15ea571..8fd437f26 100644 --- a/src/libutil/args.cc +++ b/src/libutil/args.cc @@ -164,7 +164,7 @@ Args::FlagMaker & Args::FlagMaker::mkHashTypeFlag(HashType * ht) description("hash algorithm ('md5', 'sha1', 'sha256', or 'sha512')"); handler([ht](std::string s) { *ht = parseHashType(s); - if (*ht == htUnknown) + if (*ht == HashType::Unknown) throw UsageError("unknown hash type '%1%'", s); }); return *this; diff --git a/src/libutil/args.hh b/src/libutil/args.hh index 967efbe1c..afa493663 100644 --- a/src/libutil/args.hh +++ b/src/libutil/args.hh @@ -10,7 +10,7 @@ namespace nix { MakeError(UsageError, Error); -enum HashType : char; +enum struct HashType : char; class Args { diff --git a/src/libutil/compression.cc b/src/libutil/compression.cc index 860b04adb..75e889f41 100644 --- a/src/libutil/compression.cc +++ b/src/libutil/compression.cc @@ -314,7 +314,7 @@ struct XzCompressionSink : CompressionSink ret = lzma_stream_encoder_mt(&strm, &mt_options); done = true; #else - printMsg(lvlError, "warning: parallel XZ compression requested but not supported, falling back to single-threaded compression"); + printMsg(Verbosity::Error, "warning: parallel XZ compression requested but not supported, falling back to single-threaded compression"); #endif } diff --git a/src/libutil/hash.cc b/src/libutil/hash.cc index 7caee1da7..5e6edeec3 100644 --- a/src/libutil/hash.cc +++ b/src/libutil/hash.cc @@ -18,10 +18,10 @@ namespace nix { void Hash::init() { - if (type == htMD5) hashSize = md5HashSize; - else if (type == htSHA1) hashSize = sha1HashSize; - else if (type == htSHA256) hashSize = sha256HashSize; - else if (type == htSHA512) hashSize = sha512HashSize; + if (type == HashType::MD5) hashSize = md5HashSize; + else if (type == HashType::SHA1) hashSize = sha1HashSize; + else if (type == HashType::SHA256) hashSize = sha256HashSize; + else if (type == HashType::SHA512) hashSize = sha512HashSize; else abort(); assert(hashSize <= maxHashSize); memset(hash, 0, maxHashSize); @@ -98,26 +98,26 @@ static string printHash32(const Hash & hash) string printHash16or32(const Hash & hash) { - return hash.to_string(hash.type == htMD5 ? Base16 : Base32, false); + return hash.to_string(hash.type == HashType::MD5 ? Base::Base16 : Base::Base32, false); } std::string Hash::to_string(Base base, bool includeType) const { std::string s; - if (base == SRI || includeType) { + if (base == Base::SRI || includeType) { s += printHashType(type); - s += base == SRI ? '-' : ':'; + s += base == Base::SRI ? '-' : ':'; } switch (base) { - case Base16: + case Base::Base16: s += printHash16(*this); break; - case Base32: + case Base::Base32: s += printHash32(*this); break; - case Base64: - case SRI: + case Base::Base64: + case Base::SRI: s += base64Encode(std::string((const char *) hash, hashSize)); break; } @@ -136,16 +136,16 @@ Hash::Hash(const std::string & s, HashType type) sep = s.find('-'); if (sep != string::npos) { isSRI = true; - } else if (type == htUnknown) + } else if (type == HashType::Unknown) throw BadHash("hash '%s' does not include a type", s); } if (sep != string::npos) { string hts = string(s, 0, sep); this->type = parseHashType(hts); - if (this->type == htUnknown) + if (this->type == HashType::Unknown) throw BadHash("unknown hash type '%s'", hts); - if (type != htUnknown && type != this->type) + if (type != HashType::Unknown && type != this->type) throw BadHash("hash '%s' should have type '%s'", s, printHashType(type)); pos = sep + 1; } @@ -217,29 +217,29 @@ union Ctx static void start(HashType ht, Ctx & ctx) { - if (ht == htMD5) MD5_Init(&ctx.md5); - else if (ht == htSHA1) SHA1_Init(&ctx.sha1); - else if (ht == htSHA256) SHA256_Init(&ctx.sha256); - else if (ht == htSHA512) SHA512_Init(&ctx.sha512); + if (ht == HashType::MD5) MD5_Init(&ctx.md5); + else if (ht == HashType::SHA1) SHA1_Init(&ctx.sha1); + else if (ht == HashType::SHA256) SHA256_Init(&ctx.sha256); + else if (ht == HashType::SHA512) SHA512_Init(&ctx.sha512); } static void update(HashType ht, Ctx & ctx, const unsigned char * bytes, size_t len) { - if (ht == htMD5) MD5_Update(&ctx.md5, bytes, len); - else if (ht == htSHA1) SHA1_Update(&ctx.sha1, bytes, len); - else if (ht == htSHA256) SHA256_Update(&ctx.sha256, bytes, len); - else if (ht == htSHA512) SHA512_Update(&ctx.sha512, bytes, len); + if (ht == HashType::MD5) MD5_Update(&ctx.md5, bytes, len); + else if (ht == HashType::SHA1) SHA1_Update(&ctx.sha1, bytes, len); + else if (ht == HashType::SHA256) SHA256_Update(&ctx.sha256, bytes, len); + else if (ht == HashType::SHA512) SHA512_Update(&ctx.sha512, bytes, len); } static void finish(HashType ht, Ctx & ctx, unsigned char * hash) { - if (ht == htMD5) MD5_Final(hash, &ctx.md5); - else if (ht == htSHA1) SHA1_Final(hash, &ctx.sha1); - else if (ht == htSHA256) SHA256_Final(hash, &ctx.sha256); - else if (ht == htSHA512) SHA512_Final(hash, &ctx.sha512); + if (ht == HashType::MD5) MD5_Final(hash, &ctx.md5); + else if (ht == HashType::SHA1) SHA1_Final(hash, &ctx.sha1); + else if (ht == HashType::SHA256) SHA256_Final(hash, &ctx.sha256); + else if (ht == HashType::SHA512) SHA512_Final(hash, &ctx.sha512); } @@ -320,20 +320,20 @@ Hash compressHash(const Hash & hash, unsigned int newSize) HashType parseHashType(const string & s) { - if (s == "md5") return htMD5; - else if (s == "sha1") return htSHA1; - else if (s == "sha256") return htSHA256; - else if (s == "sha512") return htSHA512; - else return htUnknown; + if (s == "md5") return HashType::MD5; + else if (s == "sha1") return HashType::SHA1; + else if (s == "sha256") return HashType::SHA256; + else if (s == "sha512") return HashType::SHA512; + else return HashType::Unknown; } string printHashType(HashType ht) { - if (ht == htMD5) return "md5"; - else if (ht == htSHA1) return "sha1"; - else if (ht == htSHA256) return "sha256"; - else if (ht == htSHA512) return "sha512"; + if (ht == HashType::MD5) return "md5"; + else if (ht == HashType::SHA1) return "sha1"; + else if (ht == HashType::SHA256) return "sha256"; + else if (ht == HashType::SHA512) return "sha512"; else abort(); } diff --git a/src/libutil/hash.hh b/src/libutil/hash.hh index ea9fca3e7..0fe6e7677 100644 --- a/src/libutil/hash.hh +++ b/src/libutil/hash.hh @@ -10,7 +10,13 @@ namespace nix { MakeError(BadHash, Error); -enum HashType : char { htUnknown, htMD5, htSHA1, htSHA256, htSHA512 }; +enum struct HashType : char { + Unknown, + MD5, + SHA1, + SHA256, + SHA512, +}; const int md5HashSize = 16; @@ -20,7 +26,12 @@ const int sha512HashSize = 64; extern const string base32Chars; -enum Base : int { Base64, Base32, Base16, SRI }; +enum struct Base : int { + Base64, + Base32, + Base16, + SRI, +}; struct Hash @@ -29,7 +40,7 @@ struct Hash unsigned int hashSize = 0; unsigned char hash[maxHashSize] = {}; - HashType type = htUnknown; + HashType type = HashType::Unknown; /* Create an unset hash object. */ Hash() { }; @@ -40,14 +51,14 @@ struct Hash /* Initialize the hash from a string representation, in the format "[:]" or "-" (a Subresource Integrity hash expression). If the 'type' argument - is htUnknown, then the hash type must be specified in the + is HashType::Unknown, then the hash type must be specified in the string. */ - Hash(const std::string & s, HashType type = htUnknown); + Hash(const std::string & s, HashType type = HashType::Unknown); void init(); /* Check whether a hash is set. */ - operator bool () const { return type != htUnknown; } + operator bool () const { return type != HashType::Unknown; } /* Check whether two hash are equal. */ bool operator == (const Hash & h2) const; @@ -79,18 +90,18 @@ struct Hash /* Return a string representation of the hash, in base-16, base-32 or base-64. By default, this is prefixed by the hash type (e.g. "sha256:"). */ - std::string to_string(Base base = Base32, bool includeType = true) const; + std::string to_string(Base base = Base::Base32, bool includeType = true) const; std::string gitRev() const { - assert(type == htSHA1); - return to_string(Base16, false); + assert(type == HashType::SHA1); + return to_string(Base::Base16, false); } std::string gitShortRev() const { - assert(type == htSHA1); - return std::string(to_string(Base16, false), 0, 7); + assert(type == HashType::SHA1); + return std::string(to_string(Base::Base16, false), 0, 7); } }; diff --git a/src/libutil/logging.cc b/src/libutil/logging.cc index fa5c84a27..54c73a913 100644 --- a/src/libutil/logging.cc +++ b/src/libutil/logging.cc @@ -21,7 +21,7 @@ Logger * logger = makeDefaultLogger(); void Logger::warn(const std::string & msg) { - log(lvlWarn, ANSI_YELLOW "warning:" ANSI_NORMAL " " + msg); + log(Verbosity::Warn, ANSI_YELLOW "warning:" ANSI_NORMAL " " + msg); } class SimpleLogger : public Logger @@ -45,10 +45,10 @@ public: if (systemd) { char c; switch (lvl) { - case lvlError: c = '3'; break; - case lvlWarn: c = '4'; break; - case lvlInfo: c = '5'; break; - case lvlTalkative: case lvlChatty: c = '6'; break; + case Verbosity::Error: c = '3'; break; + case Verbosity::Warn: c = '4'; break; + case Verbosity::Info: c = '5'; break; + case Verbosity::Talkative: case Verbosity::Chatty: c = '6'; break; default: c = '7'; } prefix = std::string("<") + c + ">"; @@ -66,7 +66,7 @@ public: } }; -Verbosity verbosity = lvlInfo; +Verbosity verbosity = Verbosity::Info; void warnOnce(bool & haveWarned, const FormatOrString & fs) { @@ -123,7 +123,7 @@ struct JSONLogger : Logger void write(const nlohmann::json & json) { - prevLogger.log(lvlError, "@nix " + json.dump()); + prevLogger.log(Verbosity::Error, "@nix " + json.dump()); } void log(Verbosity lvl, const FormatOrString & fs) override @@ -198,7 +198,7 @@ bool handleJSONLogMessage(const std::string & msg, if (action == "start") { auto type = (ActivityType) json["type"]; - if (trusted || type == actDownload) + if (trusted || type == ActivityType::Download) activities.emplace(std::piecewise_construct, std::forward_as_tuple(json["id"]), std::forward_as_tuple(*logger, (Verbosity) json["level"], type, @@ -216,7 +216,7 @@ bool handleJSONLogMessage(const std::string & msg, else if (action == "setPhase") { std::string phase = json["phase"]; - act.result(resSetPhase, phase); + act.result(ResultType::SetPhase, phase); } else if (action == "msg") { diff --git a/src/libutil/logging.hh b/src/libutil/logging.hh index beb5e6b64..cde525358 100644 --- a/src/libutil/logging.hh +++ b/src/libutil/logging.hh @@ -4,41 +4,41 @@ namespace nix { -typedef enum { - lvlError = 0, - lvlWarn, - lvlInfo, - lvlTalkative, - lvlChatty, - lvlDebug, - lvlVomit -} Verbosity; - -typedef enum { - actUnknown = 0, - actCopyPath = 100, - actDownload = 101, - actRealise = 102, - actCopyPaths = 103, - actBuilds = 104, - actBuild = 105, - actOptimiseStore = 106, - actVerifyPaths = 107, - actSubstitute = 108, - actQueryPathInfo = 109, - actPostBuildHook = 110, -} ActivityType; - -typedef enum { - resFileLinked = 100, - resBuildLogLine = 101, - resUntrustedPath = 102, - resCorruptedPath = 103, - resSetPhase = 104, - resProgress = 105, - resSetExpected = 106, - resPostBuildLogLine = 107, -} ResultType; +enum struct Verbosity : uint64_t { + Error = 0, + Warn, + Info, + Talkative, + Chatty, + Debug, + Vomit, +}; + +enum struct ActivityType : uint64_t { + Unknown = 0, + CopyPath = 100, + Download = 101, + Realise = 102, + CopyPaths = 103, + Builds = 104, + Build = 105, + OptimiseStore = 106, + VerifyPaths = 107, + Substitute = 108, + QueryPathInfo = 109, + PostBuildHook = 110, +}; + +enum struct ResultType : uint64_t { + FileLinked = 100, + BuildLogLine = 101, + UntrustedPath = 102, + CorruptedPath = 103, + SetPhase = 104, + Progress = 105, + SetExpected = 106, + PostBuildLogLine = 107, +}; typedef uint64_t ActivityId; @@ -67,7 +67,7 @@ public: void log(const FormatOrString & fs) { - log(lvlInfo, fs); + log(Verbosity::Info, fs); } virtual void warn(const std::string & msg); @@ -94,17 +94,17 @@ struct Activity Activity(Logger & logger, ActivityType type, const Logger::Fields & fields = {}, ActivityId parent = getCurActivity()) - : Activity(logger, lvlError, type, "", fields, parent) { }; + : Activity(logger, Verbosity::Error, type, "", fields, parent) { }; Activity(const Activity & act) = delete; ~Activity(); void progress(uint64_t done = 0, uint64_t expected = 0, uint64_t running = 0, uint64_t failed = 0) const - { result(resProgress, done, expected, running, failed); } + { result(ResultType::Progress, done, expected, running, failed); } void setExpected(ActivityType type2, uint64_t expected) const - { result(resSetExpected, type2, expected); } + { result(ResultType::SetExpected, (uint64_t)type2, expected); } template void result(ResultType type, const Args & ... args) const @@ -151,11 +151,11 @@ extern Verbosity verbosity; /* suppress msgs > this */ } \ } while (0) -#define printError(args...) printMsg(lvlError, args) -#define printInfo(args...) printMsg(lvlInfo, args) -#define printTalkative(args...) printMsg(lvlTalkative, args) -#define debug(args...) printMsg(lvlDebug, args) -#define vomit(args...) printMsg(lvlVomit, args) +#define printError(args...) printMsg(Verbosity::Error, args) +#define printInfo(args...) printMsg(Verbosity::Info, args) +#define printTalkative(args...) printMsg(Verbosity::Talkative, args) +#define debug(args...) printMsg(Verbosity::Debug, args) +#define vomit(args...) printMsg(Verbosity::Vomit, args) template inline void warn(const std::string & fs, const Args & ... args) diff --git a/src/libutil/util.cc b/src/libutil/util.cc index 097ff210a..8cabbb503 100644 --- a/src/libutil/util.cc +++ b/src/libutil/util.cc @@ -430,7 +430,7 @@ void deletePath(const Path & path) void deletePath(const Path & path, unsigned long long & bytesFreed) { - //Activity act(*logger, lvlDebug, format("recursively deleting path '%1%'") % path); + //Activity act(*logger, Verbosity::Debug, format("recursively deleting path '%1%'") % path); bytesFreed = 0; _deletePath(path, bytesFreed); } @@ -1410,7 +1410,7 @@ string base64Decode(const string & s) char digit = decode[(unsigned char) c]; if (digit == -1) - throw Error("invalid character in Base64 string"); + throw Error("invalid character in Base::Base64 string"); bits += 6; d = d << 6 | digit; diff --git a/src/libutil/util.hh b/src/libutil/util.hh index 7c3a30242..e04ce3701 100644 --- a/src/libutil/util.hh +++ b/src/libutil/util.hh @@ -468,7 +468,7 @@ std::string filterANSIEscapes(const std::string & s, unsigned int width = std::numeric_limits::max()); -/* Base64 encoding/decoding. */ +/* Base::Base64 encoding/decoding. */ string base64Encode(const string & s); string base64Decode(const string & s); -- cgit v1.2.3 From 6dd471ebf6b9a4996405398093ccb371b8abdf2f Mon Sep 17 00:00:00 2001 From: Carlo Nucera Date: Thu, 28 May 2020 11:28:43 -0400 Subject: Fixing the result of merge --- src/libutil/tests/hash.cc | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) (limited to 'src/libutil') diff --git a/src/libutil/tests/hash.cc b/src/libutil/tests/hash.cc index 7cb439817..c513ce4ac 100644 --- a/src/libutil/tests/hash.cc +++ b/src/libutil/tests/hash.cc @@ -10,28 +10,28 @@ namespace nix { TEST(hashString, testKnownMD5Hashes1) { // values taken from: https://tools.ietf.org/html/rfc1321 auto s1 = ""; - auto hash = hashString(HashType::htMD5, s1); + auto hash = hashString(HashType::MD5, s1); ASSERT_EQ(hash.to_string(Base::Base16), "md5:d41d8cd98f00b204e9800998ecf8427e"); } TEST(hashString, testKnownMD5Hashes2) { // values taken from: https://tools.ietf.org/html/rfc1321 auto s2 = "abc"; - auto hash = hashString(HashType::htMD5, s2); + auto hash = hashString(HashType::MD5, s2); ASSERT_EQ(hash.to_string(Base::Base16), "md5:900150983cd24fb0d6963f7d28e17f72"); } TEST(hashString, testKnownSHA1Hashes1) { // values taken from: https://tools.ietf.org/html/rfc3174 auto s = "abc"; - auto hash = hashString(HashType::htSHA1, s); + auto hash = hashString(HashType::SHA1, s); ASSERT_EQ(hash.to_string(Base::Base16),"sha1:a9993e364706816aba3e25717850c26c9cd0d89d"); } TEST(hashString, testKnownSHA1Hashes2) { // values taken from: https://tools.ietf.org/html/rfc3174 auto s = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"; - auto hash = hashString(HashType::htSHA1, s); + auto hash = hashString(HashType::SHA1, s); ASSERT_EQ(hash.to_string(Base::Base16),"sha1:84983e441c3bd26ebaae4aa1f95129e5e54670f1"); } @@ -39,7 +39,7 @@ namespace nix { // values taken from: https://tools.ietf.org/html/rfc4634 auto s = "abc"; - auto hash = hashString(HashType::htSHA256, s); + auto hash = hashString(HashType::SHA256, s); ASSERT_EQ(hash.to_string(Base::Base16), "sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); } @@ -47,7 +47,7 @@ namespace nix { TEST(hashString, testKnownSHA256Hashes2) { // values taken from: https://tools.ietf.org/html/rfc4634 auto s = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"; - auto hash = hashString(HashType::htSHA256, s); + auto hash = hashString(HashType::SHA256, s); ASSERT_EQ(hash.to_string(Base::Base16), "sha256:248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"); } @@ -55,7 +55,7 @@ namespace nix { TEST(hashString, testKnownSHA512Hashes1) { // values taken from: https://tools.ietf.org/html/rfc4634 auto s = "abc"; - auto hash = hashString(HashType::htSHA512, s); + auto hash = hashString(HashType::SHA512, s); ASSERT_EQ(hash.to_string(Base::Base16), "sha512:ddaf35a193617abacc417349ae20413112e6fa4e89a9" "7ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd" @@ -66,7 +66,7 @@ namespace nix { // values taken from: https://tools.ietf.org/html/rfc4634 auto s = "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"; - auto hash = hashString(HashType::htSHA512, s); + auto hash = hashString(HashType::SHA512, s); ASSERT_EQ(hash.to_string(Base::Base16), "sha512:8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa1" "7299aeadb6889018501d289e4900f7e4331b99dec4b5433a" @@ -75,6 +75,6 @@ namespace nix { TEST(hashString, hashingWithUnknownAlgoExits) { auto s = "unknown"; - ASSERT_DEATH(hashString(HashType::htUnknown, s), ""); + ASSERT_DEATH(hashString(HashType::Unknown, s), ""); } } -- cgit v1.2.3 From 450dcf2c1b60a36f5ffeab2411805287d122bcdd Mon Sep 17 00:00:00 2001 From: John Ericson Date: Tue, 2 Jun 2020 15:52:13 +0000 Subject: Remove `HashType::Unknown` Instead, `Hash` uses `std::optional`. In the future, we may also make `Hash` itself require a known hash type, encoraging people to use `std::optional` instead. --- src/libutil/args.cc | 2 -- src/libutil/hash.cc | 62 ++++++++++++++++++++++++++++++++--------------- src/libutil/hash.hh | 15 ++++++++---- src/libutil/tests/hash.cc | 2 +- 4 files changed, 53 insertions(+), 28 deletions(-) (limited to 'src/libutil') diff --git a/src/libutil/args.cc b/src/libutil/args.cc index 4a3f5aae8..c4035ab85 100644 --- a/src/libutil/args.cc +++ b/src/libutil/args.cc @@ -162,8 +162,6 @@ Args::Flag Args::Flag::mkHashTypeFlag(std::string && longName, HashType * ht) .labels = {"hash-algo"}, .handler = {[ht](std::string s) { *ht = parseHashType(s); - if (*ht == HashType::Unknown) - throw UsageError("unknown hash type '%1%'", s); }} }; } diff --git a/src/libutil/hash.cc b/src/libutil/hash.cc index 5e6edeec3..0c3de2fda 100644 --- a/src/libutil/hash.cc +++ b/src/libutil/hash.cc @@ -4,6 +4,7 @@ #include #include +#include "args.hh" #include "hash.hh" #include "archive.hh" #include "util.hh" @@ -18,11 +19,13 @@ namespace nix { void Hash::init() { - if (type == HashType::MD5) hashSize = md5HashSize; - else if (type == HashType::SHA1) hashSize = sha1HashSize; - else if (type == HashType::SHA256) hashSize = sha256HashSize; - else if (type == HashType::SHA512) hashSize = sha512HashSize; - else abort(); + if (!type) abort(); + switch (*type) { + case HashType::MD5: hashSize = md5HashSize; break; + case HashType::SHA1: hashSize = sha1HashSize; break; + case HashType::SHA256: hashSize = sha256HashSize; break; + case HashType::SHA512: hashSize = sha512HashSize; break; + } assert(hashSize <= maxHashSize); memset(hash, 0, maxHashSize); } @@ -102,11 +105,18 @@ string printHash16or32(const Hash & hash) } +HashType assertInitHashType(const Hash & h) { + if (h.type) + return *h.type; + else + abort(); +} + std::string Hash::to_string(Base base, bool includeType) const { std::string s; if (base == Base::SRI || includeType) { - s += printHashType(type); + s += printHashType(assertInitHashType(*this)); s += base == Base::SRI ? '-' : ':'; } switch (base) { @@ -124,8 +134,10 @@ std::string Hash::to_string(Base base, bool includeType) const return s; } +Hash::Hash(const std::string & s, HashType type) : Hash(s, std::optional { type }) { } +Hash::Hash(const std::string & s) : Hash(s, std::optional{}) { } -Hash::Hash(const std::string & s, HashType type) +Hash::Hash(const std::string & s, std::optional type) : type(type) { size_t pos = 0; @@ -136,17 +148,17 @@ Hash::Hash(const std::string & s, HashType type) sep = s.find('-'); if (sep != string::npos) { isSRI = true; - } else if (type == HashType::Unknown) + } else if (! type) throw BadHash("hash '%s' does not include a type", s); } if (sep != string::npos) { string hts = string(s, 0, sep); this->type = parseHashType(hts); - if (this->type == HashType::Unknown) + if (!this->type) throw BadHash("unknown hash type '%s'", hts); - if (type != HashType::Unknown && type != this->type) - throw BadHash("hash '%s' should have type '%s'", s, printHashType(type)); + if (type && type != this->type) + throw BadHash("hash '%s' should have type '%s'", s, printHashType(*type)); pos = sep + 1; } @@ -202,7 +214,7 @@ Hash::Hash(const std::string & s, HashType type) } else - throw BadHash("hash '%s' has wrong length for hash type '%s'", s, printHashType(type)); + throw BadHash("hash '%s' has wrong length for hash type '%s'", s, printHashType(*type)); } @@ -318,24 +330,34 @@ Hash compressHash(const Hash & hash, unsigned int newSize) } -HashType parseHashType(const string & s) +std::optional parseHashTypeOpt(const string & s) { if (s == "md5") return HashType::MD5; else if (s == "sha1") return HashType::SHA1; else if (s == "sha256") return HashType::SHA256; else if (s == "sha512") return HashType::SHA512; - else return HashType::Unknown; + else return std::optional {}; } +HashType parseHashType(const string & s) +{ + auto opt_h = parseHashTypeOpt(s); + if (opt_h) + return *opt_h; + else + throw UsageError("unknown hash algorithm '%1%'", s); +} string printHashType(HashType ht) { - if (ht == HashType::MD5) return "md5"; - else if (ht == HashType::SHA1) return "sha1"; - else if (ht == HashType::SHA256) return "sha256"; - else if (ht == HashType::SHA512) return "sha512"; - else abort(); + string ret; + switch (ht) { + case HashType::MD5: ret = "md5"; break; + case HashType::SHA1: ret = "sha1"; break; + case HashType::SHA256: ret = "sha256"; break; + case HashType::SHA512: ret = "sha512"; break; + } + return ret; } - } diff --git a/src/libutil/hash.hh b/src/libutil/hash.hh index 0fe6e7677..41322be67 100644 --- a/src/libutil/hash.hh +++ b/src/libutil/hash.hh @@ -11,7 +11,6 @@ MakeError(BadHash, Error); enum struct HashType : char { - Unknown, MD5, SHA1, SHA256, @@ -40,7 +39,7 @@ struct Hash unsigned int hashSize = 0; unsigned char hash[maxHashSize] = {}; - HashType type = HashType::Unknown; + std::optional type = {}; /* Create an unset hash object. */ Hash() { }; @@ -51,14 +50,18 @@ struct Hash /* Initialize the hash from a string representation, in the format "[:]" or "-" (a Subresource Integrity hash expression). If the 'type' argument - is HashType::Unknown, then the hash type must be specified in the + is not present, then the hash type must be specified in the string. */ - Hash(const std::string & s, HashType type = HashType::Unknown); + Hash(const std::string & s, std::optional type); + // type must be provided + Hash(const std::string & s, HashType type); + // hash type must be part of string + Hash(const std::string & s); void init(); /* Check whether a hash is set. */ - operator bool () const { return type != HashType::Unknown; } + operator bool () const { return (bool) type; } /* Check whether two hash are equal. */ bool operator == (const Hash & h2) const; @@ -127,6 +130,8 @@ Hash compressHash(const Hash & hash, unsigned int newSize); /* Parse a string representing a hash type. */ HashType parseHashType(const string & s); +/* Will return nothing on parse error */ +std::optional parseHashTypeOpt(const string & s); /* And the reverse. */ string printHashType(HashType ht); diff --git a/src/libutil/tests/hash.cc b/src/libutil/tests/hash.cc index c513ce4ac..5fd168be5 100644 --- a/src/libutil/tests/hash.cc +++ b/src/libutil/tests/hash.cc @@ -75,6 +75,6 @@ namespace nix { TEST(hashString, hashingWithUnknownAlgoExits) { auto s = "unknown"; - ASSERT_DEATH(hashString(HashType::Unknown, s), ""); + ASSERT_DEATH(hashString(HashType::SHA512, s), ""); } } -- cgit v1.2.3 From d73dbc8e4cfe7ad92f072f9ccc30e51df9a5e97b Mon Sep 17 00:00:00 2001 From: John Ericson Date: Tue, 2 Jun 2020 16:28:54 +0000 Subject: Remove `hashingWithUnknownAlgoExits` A valid hash type must be provided now. The hash itself can still be invalid, but that doesn't cause an `abort()`. --- src/libutil/tests/hash.cc | 5 ----- 1 file changed, 5 deletions(-) (limited to 'src/libutil') diff --git a/src/libutil/tests/hash.cc b/src/libutil/tests/hash.cc index 5fd168be5..ecc0d4a03 100644 --- a/src/libutil/tests/hash.cc +++ b/src/libutil/tests/hash.cc @@ -72,9 +72,4 @@ namespace nix { "7299aeadb6889018501d289e4900f7e4331b99dec4b5433a" "c7d329eeb6dd26545e96e55b874be909"); } - - TEST(hashString, hashingWithUnknownAlgoExits) { - auto s = "unknown"; - ASSERT_DEATH(hashString(HashType::SHA512, s), ""); - } } -- cgit v1.2.3 From c664e68b87a3e9e41c4471276886da71793b2d85 Mon Sep 17 00:00:00 2001 From: John Ericson Date: Tue, 2 Jun 2020 18:25:32 +0000 Subject: Fix to-base --type handler to correctly set std::optional flag Now that we have a separate flag function, also describe why it is optional. --- src/libutil/args.cc | 12 ++++++++++++ src/libutil/args.hh | 1 + 2 files changed, 13 insertions(+) (limited to 'src/libutil') diff --git a/src/libutil/args.cc b/src/libutil/args.cc index c4035ab85..4fe9539e4 100644 --- a/src/libutil/args.cc +++ b/src/libutil/args.cc @@ -166,6 +166,18 @@ Args::Flag Args::Flag::mkHashTypeFlag(std::string && longName, HashType * ht) }; } +Args::Flag Args::Flag::mkHashTypeOptFlag(std::string && longName, std::optional * oht) +{ + return Flag { + .longName = std::move(longName), + .description = "hash algorithm ('md5', 'sha1', 'sha256', or 'sha512'). Optional as can also be gotten from SRI hash itself.", + .labels = {"hash-algo"}, + .handler = {[oht](std::string s) { + *oht = std::optional { parseHashType(s) }; + }} + }; +} + Strings argvToStrings(int argc, char * * argv) { Strings args; diff --git a/src/libutil/args.hh b/src/libutil/args.hh index fc8f82af5..f2315f67a 100644 --- a/src/libutil/args.hh +++ b/src/libutil/args.hh @@ -85,6 +85,7 @@ protected: Handler handler; static Flag mkHashTypeFlag(std::string && longName, HashType * ht); + static Flag mkHashTypeOptFlag(std::string && longName, std::optional * oht); }; std::map longFlags; -- cgit v1.2.3 From 1fcd3afc38ebc7ee98add0bf1b4bd643b25ccebf Mon Sep 17 00:00:00 2001 From: John Ericson Date: Tue, 2 Jun 2020 20:35:17 +0000 Subject: Fix hashes --- src/libutil/hash.cc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src/libutil') diff --git a/src/libutil/hash.cc b/src/libutil/hash.cc index 0c3de2fda..6b9effdd2 100644 --- a/src/libutil/hash.cc +++ b/src/libutil/hash.cc @@ -19,13 +19,13 @@ namespace nix { void Hash::init() { - if (!type) abort(); - switch (*type) { + if (!type) abort(); + switch (*type) { case HashType::MD5: hashSize = md5HashSize; break; case HashType::SHA1: hashSize = sha1HashSize; break; case HashType::SHA256: hashSize = sha256HashSize; break; case HashType::SHA512: hashSize = sha512HashSize; break; - } + } assert(hashSize <= maxHashSize); memset(hash, 0, maxHashSize); } -- cgit v1.2.3 From cd6dbf951a0ea903d0e9f2671fb127ae419e5ed2 Mon Sep 17 00:00:00 2001 From: Tobias Pflug Date: Mon, 8 Jun 2020 11:34:37 +0200 Subject: Add compression unit tests --- src/libutil/tests/compression.cc | 78 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 src/libutil/tests/compression.cc (limited to 'src/libutil') diff --git a/src/libutil/tests/compression.cc b/src/libutil/tests/compression.cc new file mode 100644 index 000000000..5b7a2c5b9 --- /dev/null +++ b/src/libutil/tests/compression.cc @@ -0,0 +1,78 @@ +#include "compression.hh" +#include + +namespace nix { + + /* ---------------------------------------------------------------------------- + * compress / decompress + * --------------------------------------------------------------------------*/ + + TEST(compress, compressWithUnknownMethod) { + ASSERT_THROW(compress("invalid-method", "something-to-compress"), UnknownCompressionMethod); + } + + TEST(compress, noneMethodDoesNothingToTheInput) { + ref o = compress("none", "this-is-a-test"); + + ASSERT_EQ(*o, "this-is-a-test"); + } + + TEST(decompress, decompressXzCompressed) { + auto method = "xz"; + auto str = "slfja;sljfklsa;jfklsjfkl;sdjfkl;sadjfkl;sdjf;lsdfjsadlf"; + ref o = decompress(method, *compress(method, str)); + + ASSERT_EQ(*o, str); + } + + TEST(decompress, decompressBzip2Compressed) { + auto method = "bzip2"; + auto str = "slfja;sljfklsa;jfklsjfkl;sdjfkl;sadjfkl;sdjf;lsdfjsadlf"; + ref o = decompress(method, *compress(method, str)); + + ASSERT_EQ(*o, str); + } + + TEST(decompress, decompressBrCompressed) { + auto method = "br"; + auto str = "slfja;sljfklsa;jfklsjfkl;sdjfkl;sadjfkl;sdjf;lsdfjsadlf"; + ref o = decompress(method, *compress(method, str)); + + ASSERT_EQ(*o, str); + } + + TEST(decompress, decompressInvalidInputThrowsCompressionError) { + auto method = "bzip2"; + auto str = "this is a string that does not qualify as valid bzip2 data"; + + ASSERT_THROW(decompress(method, str), CompressionError); + } + + /* ---------------------------------------------------------------------------- + * compression sinks + * --------------------------------------------------------------------------*/ + + TEST(makeCompressionSink, noneSinkDoesNothingToInput) { + StringSink strSink; + auto inputString = "slfja;sljfklsa;jfklsjfkl;sdjfkl;sadjfkl;sdjf;lsdfjsadlf"; + auto sink = makeCompressionSink("none", strSink); + (*sink)(inputString); + sink->finish(); + + ASSERT_STREQ((*strSink.s).c_str(), inputString); + } + + TEST(makeCompressionSink, compressAndDecompress) { + StringSink strSink; + auto inputString = "slfja;sljfklsa;jfklsjfkl;sdjfkl;sadjfkl;sdjf;lsdfjsadlf"; + auto decompressionSink = makeDecompressionSink("bzip2", strSink); + auto sink = makeCompressionSink("bzip2", *decompressionSink); + + (*sink)(inputString); + sink->finish(); + decompressionSink->finish(); + + ASSERT_STREQ((*strSink.s).c_str(), inputString); + } + +} -- cgit v1.2.3 From c9d06558b6cfb30cb6ad7d872ec1046434645b3b Mon Sep 17 00:00:00 2001 From: p01arst0rm Date: Wed, 17 Jun 2020 03:15:47 +0100 Subject: replaced uncaught_exception with uncaught_exceptions --- src/libutil/json.cc | 2 +- src/libutil/util.cc | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src/libutil') diff --git a/src/libutil/json.cc b/src/libutil/json.cc index 74e37b4c4..01331947e 100644 --- a/src/libutil/json.cc +++ b/src/libutil/json.cc @@ -173,7 +173,7 @@ JSONObject JSONPlaceholder::object() JSONPlaceholder::~JSONPlaceholder() { - assert(!first || std::uncaught_exception()); + assert(!first || std::uncaught_exceptions()); } } diff --git a/src/libutil/util.cc b/src/libutil/util.cc index 667dd2edb..6ca9013a4 100644 --- a/src/libutil/util.cc +++ b/src/libutil/util.cc @@ -1199,7 +1199,7 @@ void _interrupted() /* Block user interrupts while an exception is being handled. Throwing an exception while another exception is being handled kills the program! */ - if (!interruptThrown && !std::uncaught_exception()) { + if (!interruptThrown && !std::uncaught_exceptions()) { interruptThrown = true; throw Interrupted("interrupted by the user"); } -- cgit v1.2.3 From e9970a34e8841faaecd39ba18e0913101beca592 Mon Sep 17 00:00:00 2001 From: p01arst0rm Date: Wed, 17 Jun 2020 03:19:15 +0100 Subject: appended ' __attribute__((weak)); ' to 'extern char * * environ ' --- src/libutil/util.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/libutil') diff --git a/src/libutil/util.cc b/src/libutil/util.cc index 667dd2edb..85246ced6 100644 --- a/src/libutil/util.cc +++ b/src/libutil/util.cc @@ -35,7 +35,7 @@ #endif -extern char * * environ; +extern char * * environ __attribute__((weak)); namespace nix { -- cgit v1.2.3 From 6403508f5a2fcf073b2a0d4e5fcf5f5ebb890384 Mon Sep 17 00:00:00 2001 From: John Ericson Date: Wed, 17 Jun 2020 15:13:00 +0000 Subject: Use `ansicolor.hh` in `nix repl` rather than duplicates --- src/libutil/ansicolor.hh | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src/libutil') diff --git a/src/libutil/ansicolor.hh b/src/libutil/ansicolor.hh index 8ae07b092..a38c2d798 100644 --- a/src/libutil/ansicolor.hh +++ b/src/libutil/ansicolor.hh @@ -11,5 +11,7 @@ namespace nix { #define ANSI_GREEN "\e[32;1m" #define ANSI_YELLOW "\e[33;1m" #define ANSI_BLUE "\e[34;1m" +#define ANSI_MAGENTA "\e[35m;1m" +#define ANSI_CYAN "\e[36m;1m" } -- cgit v1.2.3 From 15abb2aa2ba7de06a86e05511f81633616e17d87 Mon Sep 17 00:00:00 2001 From: John Ericson Date: Thu, 18 Jun 2020 22:09:22 +0000 Subject: Revert the `enum struct` change Not a regular git revert as there have been many merges and things. --- src/libutil/args.hh | 2 +- src/libutil/compression.cc | 2 +- src/libutil/error.cc | 16 +++++----- src/libutil/error.hh | 24 +++++++------- src/libutil/hash.cc | 67 +++++++++++++++++++------------------- src/libutil/hash.hh | 22 ++++--------- src/libutil/logging.cc | 22 ++++++------- src/libutil/logging.hh | 76 ++++++++++++++++++++++---------------------- src/libutil/tests/hash.cc | 16 +++++----- src/libutil/tests/logging.cc | 18 +++++------ src/libutil/util.cc | 4 +-- 11 files changed, 130 insertions(+), 139 deletions(-) (limited to 'src/libutil') diff --git a/src/libutil/args.hh b/src/libutil/args.hh index 73991881d..433d26bba 100644 --- a/src/libutil/args.hh +++ b/src/libutil/args.hh @@ -10,7 +10,7 @@ namespace nix { MakeError(UsageError, Error); -enum struct HashType : char; +enum HashType : char; class Args { diff --git a/src/libutil/compression.cc b/src/libutil/compression.cc index 9f270c8f3..a117ddc72 100644 --- a/src/libutil/compression.cc +++ b/src/libutil/compression.cc @@ -314,7 +314,7 @@ struct XzCompressionSink : CompressionSink ret = lzma_stream_encoder_mt(&strm, &mt_options); done = true; #else - printMsg(Verbosity::Error, "warning: parallel XZ compression requested but not supported, falling back to single-threaded compression"); + printMsg(lvlError, "warning: parallel XZ compression requested but not supported, falling back to single-threaded compression"); #endif } diff --git a/src/libutil/error.cc b/src/libutil/error.cc index 5c2f9ed3f..0fad9ae42 100644 --- a/src/libutil/error.cc +++ b/src/libutil/error.cc @@ -110,50 +110,50 @@ std::ostream& operator<<(std::ostream &out, const ErrorInfo &einfo) string levelString; switch (einfo.level) { - case Verbosity::Error: { + case Verbosity::lvlError: { levelString = ANSI_RED; levelString += "error:"; levelString += ANSI_NORMAL; break; } - case Verbosity::Warn: { + case Verbosity::lvlWarn: { levelString = ANSI_YELLOW; levelString += "warning:"; levelString += ANSI_NORMAL; break; } - case Verbosity::Info: { + case Verbosity::lvlInfo: { levelString = ANSI_GREEN; levelString += "info:"; levelString += ANSI_NORMAL; break; } - case Verbosity::Talkative: { + case Verbosity::lvlTalkative: { levelString = ANSI_GREEN; levelString += "talk:"; levelString += ANSI_NORMAL; break; } - case Verbosity::Chatty: { + case Verbosity::lvlChatty: { levelString = ANSI_GREEN; levelString += "chat:"; levelString += ANSI_NORMAL; break; } - case Verbosity::Vomit: { + case Verbosity::lvlVomit: { levelString = ANSI_GREEN; levelString += "vomit:"; levelString += ANSI_NORMAL; break; } - case Verbosity::Debug: { + case Verbosity::lvlDebug: { levelString = ANSI_YELLOW; levelString += "debug:"; levelString += ANSI_NORMAL; break; } default: { - levelString = fmt("invalid error level: %d", (uint8_t)einfo.level); + levelString = fmt("invalid error level: %1%", einfo.level); break; } } diff --git a/src/libutil/error.hh b/src/libutil/error.hh index 4f9df826f..1e6102ce1 100644 --- a/src/libutil/error.hh +++ b/src/libutil/error.hh @@ -40,15 +40,15 @@ See the error-demo.cc program for usage examples. */ -enum struct Verbosity { - Error = 0, - Warn, - Info, - Talkative, - Chatty, - Debug, - Vomit, -}; +typedef enum { + lvlError = 0, + lvlWarn, + lvlInfo, + lvlTalkative, + lvlChatty, + lvlDebug, + lvlVomit +} Verbosity; // ErrPos indicates the location of an error in a nix file. struct ErrPos { @@ -113,7 +113,7 @@ public: template BaseError(unsigned int status, const Args & ... args) - : err { .level = Verbosity::Error, + : err { .level = lvlError, .hint = hintfmt(args...) } , status(status) @@ -121,13 +121,13 @@ public: template BaseError(const std::string & fs, const Args & ... args) - : err { .level = Verbosity::Error, + : err { .level = lvlError, .hint = hintfmt(fs, args...) } { } BaseError(hintformat hint) - : err { .level = Verbosity::Error, + : err { .level = lvlError, .hint = hint } { } diff --git a/src/libutil/hash.cc b/src/libutil/hash.cc index 106b47ae3..7a8d091df 100644 --- a/src/libutil/hash.cc +++ b/src/libutil/hash.cc @@ -21,10 +21,10 @@ void Hash::init() { if (!type) abort(); switch (*type) { - case HashType::MD5: hashSize = md5HashSize; break; - case HashType::SHA1: hashSize = sha1HashSize; break; - case HashType::SHA256: hashSize = sha256HashSize; break; - case HashType::SHA512: hashSize = sha512HashSize; break; + case htMD5: hashSize = md5HashSize; break; + case htSHA1: hashSize = sha1HashSize; break; + case htSHA256: hashSize = sha256HashSize; break; + case htSHA512: hashSize = sha512HashSize; break; } assert(hashSize <= maxHashSize); memset(hash, 0, maxHashSize); @@ -101,7 +101,7 @@ static string printHash32(const Hash & hash) string printHash16or32(const Hash & hash) { - return hash.to_string(hash.type == HashType::MD5 ? Base::Base16 : Base::Base32, false); + return hash.to_string(hash.type == htMD5 ? Base16 : Base32, false); } @@ -115,19 +115,19 @@ HashType assertInitHashType(const Hash & h) { std::string Hash::to_string(Base base, bool includeType) const { std::string s; - if (base == Base::SRI || includeType) { + if (base == SRI || includeType) { s += printHashType(assertInitHashType(*this)); - s += base == Base::SRI ? '-' : ':'; + s += base == SRI ? '-' : ':'; } switch (base) { - case Base::Base16: + case Base16: s += printHash16(*this); break; - case Base::Base32: + case Base32: s += printHash32(*this); break; - case Base::Base64: - case Base::SRI: + case Base64: + case SRI: s += base64Encode(std::string((const char *) hash, hashSize)); break; } @@ -241,29 +241,29 @@ union Ctx static void start(HashType ht, Ctx & ctx) { - if (ht == HashType::MD5) MD5_Init(&ctx.md5); - else if (ht == HashType::SHA1) SHA1_Init(&ctx.sha1); - else if (ht == HashType::SHA256) SHA256_Init(&ctx.sha256); - else if (ht == HashType::SHA512) SHA512_Init(&ctx.sha512); + if (ht == htMD5) MD5_Init(&ctx.md5); + else if (ht == htSHA1) SHA1_Init(&ctx.sha1); + else if (ht == htSHA256) SHA256_Init(&ctx.sha256); + else if (ht == htSHA512) SHA512_Init(&ctx.sha512); } static void update(HashType ht, Ctx & ctx, const unsigned char * bytes, size_t len) { - if (ht == HashType::MD5) MD5_Update(&ctx.md5, bytes, len); - else if (ht == HashType::SHA1) SHA1_Update(&ctx.sha1, bytes, len); - else if (ht == HashType::SHA256) SHA256_Update(&ctx.sha256, bytes, len); - else if (ht == HashType::SHA512) SHA512_Update(&ctx.sha512, bytes, len); + if (ht == htMD5) MD5_Update(&ctx.md5, bytes, len); + else if (ht == htSHA1) SHA1_Update(&ctx.sha1, bytes, len); + else if (ht == htSHA256) SHA256_Update(&ctx.sha256, bytes, len); + else if (ht == htSHA512) SHA512_Update(&ctx.sha512, bytes, len); } static void finish(HashType ht, Ctx & ctx, unsigned char * hash) { - if (ht == HashType::MD5) MD5_Final(hash, &ctx.md5); - else if (ht == HashType::SHA1) SHA1_Final(hash, &ctx.sha1); - else if (ht == HashType::SHA256) SHA256_Final(hash, &ctx.sha256); - else if (ht == HashType::SHA512) SHA512_Final(hash, &ctx.sha512); + if (ht == htMD5) MD5_Final(hash, &ctx.md5); + else if (ht == htSHA1) SHA1_Final(hash, &ctx.sha1); + else if (ht == htSHA256) SHA256_Final(hash, &ctx.sha256); + else if (ht == htSHA512) SHA512_Final(hash, &ctx.sha512); } @@ -344,10 +344,10 @@ Hash compressHash(const Hash & hash, unsigned int newSize) std::optional parseHashTypeOpt(const string & s) { - if (s == "md5") return HashType::MD5; - else if (s == "sha1") return HashType::SHA1; - else if (s == "sha256") return HashType::SHA256; - else if (s == "sha512") return HashType::SHA512; + if (s == "md5") return htMD5; + else if (s == "sha1") return htSHA1; + else if (s == "sha256") return htSHA256; + else if (s == "sha512") return htSHA512; else return std::optional {}; } @@ -362,14 +362,15 @@ HashType parseHashType(const string & s) string printHashType(HashType ht) { - string ret; switch (ht) { - case HashType::MD5: ret = "md5"; break; - case HashType::SHA1: ret = "sha1"; break; - case HashType::SHA256: ret = "sha256"; break; - case HashType::SHA512: ret = "sha512"; break; + case htMD5: return "md5"; break; + case htSHA1: return "sha1"; break; + case htSHA256: return "sha256"; break; + case htSHA512: return "sha512"; break; } - return ret; + // illegal hash type enum value internally, as opposed to external input + // which should be validated with nice error message. + abort(); } } diff --git a/src/libutil/hash.hh b/src/libutil/hash.hh index 8f9364440..0d9916508 100644 --- a/src/libutil/hash.hh +++ b/src/libutil/hash.hh @@ -10,12 +10,7 @@ namespace nix { MakeError(BadHash, Error); -enum struct HashType : char { - MD5, - SHA1, - SHA256, - SHA512, -}; +enum HashType : char { htMD5, htSHA1, htSHA256, htSHA512 }; const int md5HashSize = 16; @@ -25,12 +20,7 @@ const int sha512HashSize = 64; extern const string base32Chars; -enum struct Base { - Base64, - Base32, - Base16, - SRI, -}; +enum Base : int { Base64, Base32, Base16, SRI }; struct Hash @@ -97,14 +87,14 @@ struct Hash std::string gitRev() const { - assert(type == HashType::SHA1); - return to_string(Base::Base16, false); + assert(type == htSHA1); + return to_string(Base16, false); } std::string gitShortRev() const { - assert(type == HashType::SHA1); - return std::string(to_string(Base::Base16, false), 0, 7); + assert(type == htSHA1); + return std::string(to_string(Base16, false), 0, 7); } }; diff --git a/src/libutil/logging.cc b/src/libutil/logging.cc index 04156151f..105fadb15 100644 --- a/src/libutil/logging.cc +++ b/src/libutil/logging.cc @@ -22,7 +22,7 @@ Logger * logger = makeSimpleLogger(true); void Logger::warn(const std::string & msg) { - log(Verbosity::Warn, ANSI_YELLOW "warning:" ANSI_NORMAL " " + msg); + log(lvlWarn, ANSI_YELLOW "warning:" ANSI_NORMAL " " + msg); } void Logger::writeToStdout(std::string_view s) @@ -57,10 +57,10 @@ public: if (systemd) { char c; switch (lvl) { - case Verbosity::Error: c = '3'; break; - case Verbosity::Warn: c = '4'; break; - case Verbosity::Info: c = '5'; break; - case Verbosity::Talkative: case Verbosity::Chatty: c = '6'; break; + case lvlError: c = '3'; break; + case lvlWarn: c = '4'; break; + case lvlInfo: c = '5'; break; + case lvlTalkative: case lvlChatty: c = '6'; break; default: c = '7'; } prefix = std::string("<") + c + ">"; @@ -87,18 +87,18 @@ public: void result(ActivityId act, ResultType type, const Fields & fields) override { - if (type == ResultType::BuildLogLine && printBuildLogs) { + if (type == resBuildLogLine && printBuildLogs) { auto lastLine = fields[0].s; printError(lastLine); } - else if (type == ResultType::PostBuildLogLine && printBuildLogs) { + else if (type == resPostBuildLogLine && printBuildLogs) { auto lastLine = fields[0].s; printError("post-build-hook: " + lastLine); } } }; -Verbosity verbosity = Verbosity::Info; +Verbosity verbosity = lvlInfo; void warnOnce(bool & haveWarned, const FormatOrString & fs) { @@ -158,7 +158,7 @@ struct JSONLogger : Logger { void write(const nlohmann::json & json) { - prevLogger.log(Verbosity::Error, "@nix " + json.dump()); + prevLogger.log(lvlError, "@nix " + json.dump()); } void log(Verbosity lvl, const FormatOrString & fs) override @@ -246,7 +246,7 @@ bool handleJSONLogMessage(const std::string & msg, if (action == "start") { auto type = (ActivityType) json["type"]; - if (trusted || type == ActivityType::Download) + if (trusted || type == actFileTransfer) activities.emplace(std::piecewise_construct, std::forward_as_tuple(json["id"]), std::forward_as_tuple(*logger, (Verbosity) json["level"], type, @@ -264,7 +264,7 @@ bool handleJSONLogMessage(const std::string & msg, else if (action == "setPhase") { std::string phase = json["phase"]; - act.result(ResultType::SetPhase, phase); + act.result(resSetPhase, phase); } else if (action == "msg") { diff --git a/src/libutil/logging.hh b/src/libutil/logging.hh index 3b54101f0..b1583eced 100644 --- a/src/libutil/logging.hh +++ b/src/libutil/logging.hh @@ -5,32 +5,32 @@ namespace nix { -enum struct ActivityType { - Unknown = 0, - CopyPath = 100, - Download = 101, - Realise = 102, - CopyPaths = 103, - Builds = 104, - Build = 105, - OptimiseStore = 106, - VerifyPaths = 107, - Substitute = 108, - QueryPathInfo = 109, - PostBuildHook = 110, - BuildWaiting = 111, -}; - -enum struct ResultType { - FileLinked = 100, - BuildLogLine = 101, - UntrustedPath = 102, - CorruptedPath = 103, - SetPhase = 104, - Progress = 105, - SetExpected = 106, - PostBuildLogLine = 107, -}; +typedef enum { + actUnknown = 0, + actCopyPath = 100, + actFileTransfer = 101, + actRealise = 102, + actCopyPaths = 103, + actBuilds = 104, + actBuild = 105, + actOptimiseStore = 106, + actVerifyPaths = 107, + actSubstitute = 108, + actQueryPathInfo = 109, + actPostBuildHook = 110, + actBuildWaiting = 111, +} ActivityType; + +typedef enum { + resFileLinked = 100, + resBuildLogLine = 101, + resUntrustedPath = 102, + resCorruptedPath = 103, + resSetPhase = 104, + resProgress = 105, + resSetExpected = 106, + resPostBuildLogLine = 107, +} ResultType; typedef uint64_t ActivityId; @@ -64,7 +64,7 @@ public: void log(const FormatOrString & fs) { - log(Verbosity::Info, fs); + log(lvlInfo, fs); } virtual void logEI(const ErrorInfo &ei) = 0; @@ -109,17 +109,17 @@ struct Activity Activity(Logger & logger, ActivityType type, const Logger::Fields & fields = {}, ActivityId parent = getCurActivity()) - : Activity(logger, Verbosity::Error, type, "", fields, parent) { }; + : Activity(logger, lvlError, type, "", fields, parent) { }; Activity(const Activity & act) = delete; ~Activity(); void progress(uint64_t done = 0, uint64_t expected = 0, uint64_t running = 0, uint64_t failed = 0) const - { result(ResultType::Progress, done, expected, running, failed); } + { result(resProgress, done, expected, running, failed); } void setExpected(ActivityType type2, uint64_t expected) const - { result(ResultType::SetExpected, (uint64_t)type2, expected); } + { result(resSetExpected, type2, expected); } template void result(ResultType type, const Args & ... args) const @@ -167,8 +167,8 @@ extern Verbosity verbosity; /* suppress msgs > this */ } \ } while (0) -#define logError(errorInfo...) logErrorInfo(Verbosity::Error, errorInfo) -#define logWarning(errorInfo...) logErrorInfo(Verbosity::Warn, errorInfo) +#define logError(errorInfo...) logErrorInfo(lvlError, errorInfo) +#define logWarning(errorInfo...) logErrorInfo(lvlWarn, errorInfo) /* Print a string message if the current log level is at least the specified level. Note that this has to be implemented as a macro to ensure that the @@ -180,13 +180,13 @@ extern Verbosity verbosity; /* suppress msgs > this */ } \ } while (0) -#define printError(args...) printMsg(Verbosity::Error, args) -#define printInfo(args...) printMsg(Verbosity::Info, args) -#define printTalkative(args...) printMsg(Verbosity::Talkative, args) -#define debug(args...) printMsg(Verbosity::Debug, args) -#define vomit(args...) printMsg(Verbosity::Vomit, args) +#define printError(args...) printMsg(lvlError, args) +#define printInfo(args...) printMsg(lvlInfo, args) +#define printTalkative(args...) printMsg(lvlTalkative, args) +#define debug(args...) printMsg(lvlDebug, args) +#define vomit(args...) printMsg(lvlVomit, args) -/* if verbosity >= Verbosity::Warn, print a message with a yellow 'warning:' prefix. */ +/* if verbosity >= lvlWarn, print a message with a yellow 'warning:' prefix. */ template inline void warn(const std::string & fs, const Args & ... args) { diff --git a/src/libutil/tests/hash.cc b/src/libutil/tests/hash.cc index 84a50d61b..412c03030 100644 --- a/src/libutil/tests/hash.cc +++ b/src/libutil/tests/hash.cc @@ -10,28 +10,28 @@ namespace nix { TEST(hashString, testKnownMD5Hashes1) { // values taken from: https://tools.ietf.org/html/rfc1321 auto s1 = ""; - auto hash = hashString(HashType::MD5, s1); + auto hash = hashString(HashType::htMD5, s1); ASSERT_EQ(hash.to_string(Base::Base16, true), "md5:d41d8cd98f00b204e9800998ecf8427e"); } TEST(hashString, testKnownMD5Hashes2) { // values taken from: https://tools.ietf.org/html/rfc1321 auto s2 = "abc"; - auto hash = hashString(HashType::MD5, s2); + auto hash = hashString(HashType::htMD5, s2); ASSERT_EQ(hash.to_string(Base::Base16, true), "md5:900150983cd24fb0d6963f7d28e17f72"); } TEST(hashString, testKnownSHA1Hashes1) { // values taken from: https://tools.ietf.org/html/rfc3174 auto s = "abc"; - auto hash = hashString(HashType::SHA1, s); + auto hash = hashString(HashType::htSHA1, s); ASSERT_EQ(hash.to_string(Base::Base16, true),"sha1:a9993e364706816aba3e25717850c26c9cd0d89d"); } TEST(hashString, testKnownSHA1Hashes2) { // values taken from: https://tools.ietf.org/html/rfc3174 auto s = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"; - auto hash = hashString(HashType::SHA1, s); + auto hash = hashString(HashType::htSHA1, s); ASSERT_EQ(hash.to_string(Base::Base16, true),"sha1:84983e441c3bd26ebaae4aa1f95129e5e54670f1"); } @@ -39,7 +39,7 @@ namespace nix { // values taken from: https://tools.ietf.org/html/rfc4634 auto s = "abc"; - auto hash = hashString(HashType::SHA256, s); + auto hash = hashString(HashType::htSHA256, s); ASSERT_EQ(hash.to_string(Base::Base16, true), "sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); } @@ -47,7 +47,7 @@ namespace nix { TEST(hashString, testKnownSHA256Hashes2) { // values taken from: https://tools.ietf.org/html/rfc4634 auto s = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"; - auto hash = hashString(HashType::SHA256, s); + auto hash = hashString(HashType::htSHA256, s); ASSERT_EQ(hash.to_string(Base::Base16, true), "sha256:248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"); } @@ -55,7 +55,7 @@ namespace nix { TEST(hashString, testKnownSHA512Hashes1) { // values taken from: https://tools.ietf.org/html/rfc4634 auto s = "abc"; - auto hash = hashString(HashType::SHA512, s); + auto hash = hashString(HashType::htSHA512, s); ASSERT_EQ(hash.to_string(Base::Base16, true), "sha512:ddaf35a193617abacc417349ae20413112e6fa4e89a9" "7ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd" @@ -66,7 +66,7 @@ namespace nix { // values taken from: https://tools.ietf.org/html/rfc4634 auto s = "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"; - auto hash = hashString(HashType::SHA512, s); + auto hash = hashString(HashType::htSHA512, s); ASSERT_EQ(hash.to_string(Base::Base16, true), "sha512:8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa1" "7299aeadb6889018501d289e4900f7e4331b99dec4b5433a" diff --git a/src/libutil/tests/logging.cc b/src/libutil/tests/logging.cc index 2ffcbc41d..4cb54995b 100644 --- a/src/libutil/tests/logging.cc +++ b/src/libutil/tests/logging.cc @@ -68,7 +68,7 @@ namespace nix { TEST(logEI, loggingErrorOnInfoLevel) { testing::internal::CaptureStderr(); - logger->logEI({ .level = Verbosity::Info, + logger->logEI({ .level = lvlInfo, .name = "Info name", .description = "Info description", }); @@ -78,11 +78,11 @@ namespace nix { } TEST(logEI, loggingErrorOnTalkativeLevel) { - verbosity = Verbosity::Talkative; + verbosity = lvlTalkative; testing::internal::CaptureStderr(); - logger->logEI({ .level = Verbosity::Talkative, + logger->logEI({ .level = lvlTalkative, .name = "Talkative name", .description = "Talkative description", }); @@ -92,11 +92,11 @@ namespace nix { } TEST(logEI, loggingErrorOnChattyLevel) { - verbosity = Verbosity::Chatty; + verbosity = lvlChatty; testing::internal::CaptureStderr(); - logger->logEI({ .level = Verbosity::Chatty, + logger->logEI({ .level = lvlChatty, .name = "Chatty name", .description = "Talkative description", }); @@ -106,11 +106,11 @@ namespace nix { } TEST(logEI, loggingErrorOnDebugLevel) { - verbosity = Verbosity::Debug; + verbosity = lvlDebug; testing::internal::CaptureStderr(); - logger->logEI({ .level = Verbosity::Debug, + logger->logEI({ .level = lvlDebug, .name = "Debug name", .description = "Debug description", }); @@ -120,11 +120,11 @@ namespace nix { } TEST(logEI, loggingErrorOnVomitLevel) { - verbosity = Verbosity::Vomit; + verbosity = lvlVomit; testing::internal::CaptureStderr(); - logger->logEI({ .level = Verbosity::Vomit, + logger->logEI({ .level = lvlVomit, .name = "Vomit name", .description = "Vomit description", }); diff --git a/src/libutil/util.cc b/src/libutil/util.cc index e912d4450..1268b146a 100644 --- a/src/libutil/util.cc +++ b/src/libutil/util.cc @@ -442,7 +442,7 @@ void deletePath(const Path & path) void deletePath(const Path & path, unsigned long long & bytesFreed) { - //Activity act(*logger, Verbosity::Debug, format("recursively deleting path '%1%'") % path); + //Activity act(*logger, lvlDebug, format("recursively deleting path '%1%'") % path); bytesFreed = 0; _deletePath(path, bytesFreed); } @@ -1433,7 +1433,7 @@ string base64Decode(std::string_view s) char digit = decode[(unsigned char) c]; if (digit == -1) - throw Error("invalid character in Base::Base64 string"); + throw Error("invalid character in Base64 string"); bits += 6; d = d << 6 | digit; -- cgit v1.2.3 From c1892a53168f629d5baab2313c0066cc4386842d Mon Sep 17 00:00:00 2001 From: John Ericson Date: Fri, 19 Jun 2020 17:49:57 +0000 Subject: tabs -> spaces --- src/libutil/hash.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src/libutil') diff --git a/src/libutil/hash.cc b/src/libutil/hash.cc index 7a8d091df..e49eb4569 100644 --- a/src/libutil/hash.cc +++ b/src/libutil/hash.cc @@ -368,8 +368,8 @@ string printHashType(HashType ht) case htSHA256: return "sha256"; break; case htSHA512: return "sha512"; break; } - // illegal hash type enum value internally, as opposed to external input - // which should be validated with nice error message. + // illegal hash type enum value internally, as opposed to external input + // which should be validated with nice error message. abort(); } -- cgit v1.2.3