diff --git a/src/libcmd/command.cc b/src/libcmd/command.cc index 798ef072eb1..2216d8d743c 100644 --- a/src/libcmd/command.cc +++ b/src/libcmd/command.cc @@ -1,4 +1,5 @@ #include +#include #include #include "nix/cmd/command.hh" @@ -233,7 +234,7 @@ void StorePathsCommand::run(ref store, BuiltPaths && allPaths, BuiltPaths storePaths.insert(p); auto sorted = store->topoSortPaths(storePaths); - std::reverse(sorted.begin(), sorted.end()); + std::ranges::reverse(sorted); run(store, std::move(sorted)); } @@ -408,7 +409,7 @@ void createOutLinks(const std::filesystem::path & outLink, const BuiltPaths & bu } } -void MixOutLinkBase::createOutLinksMaybe(const std::vector & buildables, ref & store) +void MixOutLinkBase::createOutLinksMaybe(std::span buildables, ref & store) { if (outLink != "") if (auto store2 = store.dynamic_pointer_cast()) diff --git a/src/libcmd/include/nix/cmd/command.hh b/src/libcmd/include/nix/cmd/command.hh index d1b528e2477..3133d6f728e 100644 --- a/src/libcmd/include/nix/cmd/command.hh +++ b/src/libcmd/include/nix/cmd/command.hh @@ -8,6 +8,7 @@ #include "nix/flake/lockfile.hh" #include +#include namespace nix { @@ -398,7 +399,7 @@ struct MixOutLinkBase : virtual Args { } - void createOutLinksMaybe(const std::vector & buildables, ref & store); + void createOutLinksMaybe(std::span buildables, ref & store); }; /** `--out-link`, `--no-link`, `createOutLinksMaybe` */ diff --git a/src/libcmd/include/nix/cmd/installables.hh b/src/libcmd/include/nix/cmd/installables.hh index 530334e037b..851bc4b1355 100644 --- a/src/libcmd/include/nix/cmd/installables.hh +++ b/src/libcmd/include/nix/cmd/installables.hh @@ -9,6 +9,7 @@ #include "nix/store/build-result.hh" #include +#include namespace nix { @@ -86,7 +87,7 @@ struct BuiltPathWithResult std::optional result; }; -BuiltPaths toBuiltPaths(const std::vector & builtPathsWithResult); +BuiltPaths toBuiltPaths(std::span builtPathsWithResult); /** * Shorthand, for less typing and helping us keep the choice of diff --git a/src/libcmd/installable-flake.cc b/src/libcmd/installable-flake.cc index 65f48fa2bb7..b319e400468 100644 --- a/src/libcmd/installable-flake.cc +++ b/src/libcmd/installable-flake.cc @@ -78,7 +78,7 @@ InstallableFlake::InstallableFlake( DerivedPathsWithInfo InstallableFlake::toDerivedPaths() { - Activity act(*logger, lvlTalkative, actUnknown, fmt("evaluating derivation '%s'", what())); + Activity act(*logger, Verbosity::Talkative, ActivityType::Unknown, fmt("evaluating derivation '%s'", what())); auto attr = getCursor(*state); diff --git a/src/libcmd/installables.cc b/src/libcmd/installables.cc index 2fa2280ea58..acdb46d2cda 100644 --- a/src/libcmd/installables.cc +++ b/src/libcmd/installables.cc @@ -584,7 +584,7 @@ static void throwBuildErrors(std::vector & buildResults, const if (!failedResult->second->errorMsg.empty()) { logError( ErrorInfo{ - .level = lvlError, + .level = Verbosity::Error, .msg = failedResult->second->errorMsg, }); } @@ -623,7 +623,7 @@ std::vector, BuiltPathWithResult>> Installable::build case Realise::Nothing: case Realise::Derivation: - printMissing(store, pathsToBuild, lvlError); + printMissing(store, pathsToBuild, Verbosity::Error); for (auto & path : pathsToBuild) { for (auto & aux : backmap[path]) { @@ -653,7 +653,7 @@ std::vector, BuiltPathWithResult>> Installable::build case Realise::Outputs: { if (settings.printMissing) - printMissing(store, pathsToBuild, lvlInfo); + printMissing(store, pathsToBuild, Verbosity::Info); auto buildResults = store->buildPathsWithResults(pathsToBuild, bMode, evalStore); throwBuildErrors(buildResults, *store); @@ -854,7 +854,7 @@ void BuiltPathsCommand::applyDefaultInstallables(std::vector & rawI rawInstallables.push_back("."); } -BuiltPaths toBuiltPaths(const std::vector & builtPathsWithResult) +BuiltPaths toBuiltPaths(std::span builtPathsWithResult) { BuiltPaths res; for (auto & i : builtPathsWithResult) diff --git a/src/libcmd/repl.cc b/src/libcmd/repl.cc index 38a0da0f818..2b4eab40fb5 100644 --- a/src/libcmd/repl.cc +++ b/src/libcmd/repl.cc @@ -219,9 +219,9 @@ ReplExitStatus NixRepl::mainLoop() } catch (IncompleteReplExpr &) { continue; } catch (Error & e) { - printMsg(lvlError, e.msg()); + printMsg(Verbosity::Error, e.msg()); } catch (Interrupted & e) { - printMsg(lvlError, e.msg()); + printMsg(Verbosity::Error, e.msg()); } // We handled the current input fully, so we should clear it diff --git a/src/libexpr-tests/value/print.cc b/src/libexpr-tests/value/print.cc index d226062197d..61ea8b40cf2 100644 --- a/src/libexpr-tests/value/print.cc +++ b/src/libexpr-tests/value/print.cc @@ -19,42 +19,42 @@ struct ValuePrintingTests : LibExprTest } }; -TEST_F(ValuePrintingTests, tInt) +TEST_F(ValuePrintingTests, printInt) { Value vInt; vInt.mkInt(10); test(vInt, "10"); } -TEST_F(ValuePrintingTests, tBool) +TEST_F(ValuePrintingTests, printBool) { Value vBool; vBool.mkBool(true); test(vBool, "true"); } -TEST_F(ValuePrintingTests, tString) +TEST_F(ValuePrintingTests, printString) { Value vString; vString.mkStringNoCopy("some-string"_sds); test(vString, "\"some-string\""); } -TEST_F(ValuePrintingTests, tPath) +TEST_F(ValuePrintingTests, printPath) { Value vPath; vPath.mkStringNoCopy("/foo"_sds); test(vPath, "\"/foo\""); } -TEST_F(ValuePrintingTests, tNull) +TEST_F(ValuePrintingTests, printNull) { Value vNull; vNull.mkNull(); test(vNull, "null"); } -TEST_F(ValuePrintingTests, tAttrs) +TEST_F(ValuePrintingTests, printAttrs) { Value vOne; vOne.mkInt(1); diff --git a/src/libexpr/eval-cache.cc b/src/libexpr/eval-cache.cc index 4cfa3dabbac..100614d6801 100644 --- a/src/libexpr/eval-cache.cc +++ b/src/libexpr/eval-cache.cc @@ -8,6 +8,8 @@ // Need specialization involving `SymbolStr` just in this one module. #include "nix/util/strings-inline.hh" +#include + namespace nix::eval_cache { CachedEvalError::CachedEvalError(ref cursor, Symbol attr) @@ -511,7 +513,7 @@ ref AttrCursor::getAttr(std::string_view name) return getAttr(root->state.symbols.create(name)); } -OrSuggestions> AttrCursor::findAlongAttrPath(const std::vector & attrPath) +OrSuggestions> AttrCursor::findAlongAttrPath(std::span attrPath) { auto res = shared_from_this(); for (auto & attr : attrPath) { @@ -685,7 +687,7 @@ std::vector AttrCursor::getAttrs() std::vector attrs; for (auto & attr : *getValue().attrs()) attrs.push_back(attr.name); - std::sort(attrs.begin(), attrs.end(), [&](Symbol a, Symbol b) { + std::ranges::sort(attrs, [&](Symbol a, Symbol b) { std::string_view sa = root->state.symbols[a], sb = root->state.symbols[b]; return sa < sb; }); diff --git a/src/libexpr/eval.cc b/src/libexpr/eval.cc index 71834f10f89..1e6e308f3b7 100644 --- a/src/libexpr/eval.cc +++ b/src/libexpr/eval.cc @@ -165,17 +165,17 @@ std::string showType(const Value & v) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wswitch-enum" switch (v.getInternalType()) { - case tString: + case InternalType::String: return v.context() ? "a string with context" : "a string"; - case tPrimOp: + case InternalType::PrimOp: return fmt("the built-in function '%s'", std::string(v.primOp()->name)); - case tPrimOpApp: + case InternalType::PrimOpApp: return fmt("the partially applied built-in function '%s'", v.primOpAppPrimOp()->name); - case tExternal: + case InternalType::External: return v.external()->showType(); - case tThunk: + case InternalType::Thunk: return v.isBlackhole() ? "a black hole" : "a thunk"; - case tApp: + case InternalType::App: return "a function application"; default: return std::string(showType(v.type())); @@ -189,11 +189,11 @@ PosIdx Value::determinePos(const PosIdx pos) const #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wswitch-enum" switch (getInternalType()) { - case tAttrs: + case InternalType::Attrs: return attrs()->pos; - case tLambda: + case InternalType::Lambda: return lambda().fun->pos; - case tApp: + case InternalType::App: return app().left->determinePos(pos); default: return pos; @@ -203,8 +203,8 @@ PosIdx Value::determinePos(const PosIdx pos) const bool Value::isTrivial() const { - return !isa() - && (!isa() + return !isa() + && (!isa() || (dynamic_cast(thunk().expr) && ((ExprAttrs *) thunk().expr)->dynamicAttrs->empty()) || dynamic_cast(thunk().expr) || dynamic_cast(thunk().expr)); } @@ -645,8 +645,8 @@ std::optional EvalState::getDoc(Value & v) void printStaticEnvBindings(const SymbolTable & st, const StaticEnv & se) { std::cout << ANSI_MAGENTA; - for (auto & i : se.vars) - std::cout << st[i.first] << " "; + for (auto & [symbol, _] : se.vars) + std::cout << st[symbol] << " "; std::cout << ANSI_NORMAL; std::cout << std::endl; } @@ -682,9 +682,9 @@ void printEnvBindings(const SymbolTable & st, const StaticEnv & se, const Env & std::cout << ANSI_MAGENTA; // for the top level, don't print the double underscore ones; // they are in builtins. - for (auto & i : se.vars) - if (!hasPrefix(st[i.first], "__")) - std::cout << st[i.first] << " "; + for (auto & [symbol, _] : se.vars) + if (!hasPrefix(st[symbol], "__")) + std::cout << st[symbol] << " "; std::cout << ANSI_NORMAL; std::cout << std::endl; if (se.isWith) @@ -715,8 +715,8 @@ void mapStaticEnvBindings(const SymbolTable & st, const StaticEnv & se, const En vm.insert_or_assign(std::string(st[j.name]), j.value); } else { // iterate through staticenv bindings and add them. - for (auto & i : se.vars) - vm.insert_or_assign(std::string(st[i.first]), env.values[i.second]); + for (auto & [symbol, displ] : se.vars) + vm.insert_or_assign(std::string(st[symbol]), env.values[displ]); } } } @@ -795,7 +795,7 @@ void EvalState::runDebugRepl(const Error * error, const Env & env, const Expr & if (error) { printError("%s\n", error->what()); - if (trylevel > 0 && error->info().level != lvlInfo) + if (trylevel > 0 && error->info().level != Verbosity::Info) printError( "This exception occurred in a 'tryEval' call. Use " ANSI_GREEN "--ignore-try" ANSI_NORMAL " to skip these.\n"); @@ -1637,7 +1637,7 @@ void EvalState::callFunction(Value & fun, std::span args, Value & vRes, size_t argsLeft = vCur.primOp()->arity; if (args.size() < argsLeft) { - /* We don't have enough arguments, so create a tPrimOpApp chain. */ + /* We don't have enough arguments, so create a InternalType::PrimOpApp chain. */ makeAppChain(); return; } else { @@ -1673,7 +1673,7 @@ void EvalState::callFunction(Value & fun, std::span args, Value & vRes, auto argsLeft = arity - argsDone; if (args.size() < argsLeft) { - /* We still don't have enough arguments, so extend the tPrimOpApp chain. */ + /* We still don't have enough arguments, so extend the InternalType::PrimOpApp chain. */ makeAppChain(); return; } else { @@ -2509,7 +2509,7 @@ StorePath EvalState::copyPathToStore(NixStringContext & context, const SourcePat repair); allowPath(dstPath); srcToStore->try_emplace(path, dstPath); - printMsg(lvlChatty, "copied source '%1%' -> '%2%'", path, store->printStorePath(dstPath)); + printMsg(Verbosity::Chatty, "copied source '%1%' -> '%2%'", path, store->printStorePath(dstPath)); return dstPath; }(); @@ -3133,7 +3133,7 @@ Expr * EvalState::parseStdin() // NOTE this method (and parseExprFromString) must take care to *fully copy* their // input into their respective Pos::Origin until the parser stops overwriting its // input data. - // Activity act(*logger, lvlTalkative, "parsing standard input"); + // Activity act(*logger, Verbosity::Talkative, "parsing standard input"); auto buffer = drainFD(0); // drainFD should have left some extra space for terminators buffer.append("\0\0", 2); diff --git a/src/libexpr/function-trace.cc b/src/libexpr/function-trace.cc index 55ccfc79126..5d09c651e92 100644 --- a/src/libexpr/function-trace.cc +++ b/src/libexpr/function-trace.cc @@ -8,7 +8,7 @@ void FunctionCallTrace::preFunctionCallHook( { auto duration = std::chrono::high_resolution_clock::now().time_since_epoch(); auto ns = std::chrono::duration_cast(duration); - printMsg(lvlInfo, "function-trace entered %1% at %2%", state.positions[pos], ns.count()); + printMsg(Verbosity::Info, "function-trace entered %1% at %2%", state.positions[pos], ns.count()); } void FunctionCallTrace::postFunctionCallHook( @@ -16,7 +16,7 @@ void FunctionCallTrace::postFunctionCallHook( { auto duration = std::chrono::high_resolution_clock::now().time_since_epoch(); auto ns = std::chrono::duration_cast(duration); - printMsg(lvlInfo, "function-trace exited %1% at %2%", state.positions[pos], ns.count()); + printMsg(Verbosity::Info, "function-trace exited %1% at %2%", state.positions[pos], ns.count()); } } // namespace nix diff --git a/src/libexpr/include/nix/expr/eval-cache.hh b/src/libexpr/include/nix/expr/eval-cache.hh index 0a0461c192a..7846ed0302e 100644 --- a/src/libexpr/include/nix/expr/eval-cache.hh +++ b/src/libexpr/include/nix/expr/eval-cache.hh @@ -6,6 +6,7 @@ #include "nix/expr/eval.hh" #include +#include #include namespace nix::eval_cache { @@ -146,7 +147,7 @@ public: * Get an attribute along a chain of attrsets. Note that this does * not auto-call functors or functions. */ - OrSuggestions> findAlongAttrPath(const std::vector & attrPath); + OrSuggestions> findAlongAttrPath(std::span attrPath); std::string getString(); diff --git a/src/libexpr/include/nix/expr/eval.hh b/src/libexpr/include/nix/expr/eval.hh index b70c9db789d..64c2b23b64b 100644 --- a/src/libexpr/include/nix/expr/eval.hh +++ b/src/libexpr/include/nix/expr/eval.hh @@ -663,9 +663,9 @@ public: /** * Force `v`, and then verify that it has the expected type. */ - NixInt forceInt(Value & v, const PosIdx pos, std::string_view errorCtx); - NixFloat forceFloat(Value & v, const PosIdx pos, std::string_view errorCtx); - bool forceBool(Value & v, const PosIdx pos, std::string_view errorCtx); + [[nodiscard]] NixInt forceInt(Value & v, const PosIdx pos, std::string_view errorCtx); + [[nodiscard]] NixFloat forceFloat(Value & v, const PosIdx pos, std::string_view errorCtx); + [[nodiscard]] bool forceBool(Value & v, const PosIdx pos, std::string_view errorCtx); void forceAttrs(Value & v, const PosIdx pos, std::string_view errorCtx); @@ -703,7 +703,7 @@ public: * @return true iff the value `v` denotes a derivation (i.e. a * set with attribute `type = "derivation"`). */ - bool isDerivation(Value & v); + [[nodiscard]] bool isDerivation(Value & v); std::optional tryAttrsToString( const PosIdx pos, Value & v, NixStringContext & context, bool coerceMore = false, bool copyToStore = true); @@ -895,7 +895,7 @@ public: */ void assertEqValues(Value & v1, Value & v2, const PosIdx pos, std::string_view errorCtx); - bool isFunctor(const Value & fun) const; + [[nodiscard]] bool isFunctor(const Value & fun) const; void callFunction(Value & fun, std::span args, Value & vRes, const PosIdx pos); diff --git a/src/libexpr/include/nix/expr/nixexpr.hh b/src/libexpr/include/nix/expr/nixexpr.hh index c7bfb7359cb..448e87b9b25 100644 --- a/src/libexpr/include/nix/expr/nixexpr.hh +++ b/src/libexpr/include/nix/expr/nixexpr.hh @@ -356,7 +356,7 @@ struct ExprOpHasAttr : Expr struct ExprAttrs : Expr { - bool recursive; + bool recursive = false; PosIdx pos; struct AttrDef @@ -419,13 +419,11 @@ struct ExprAttrs : Expr */ std::optional dynamicAttrs; ExprAttrs(const PosIdx & pos) - : recursive(false) - , pos(pos) + : pos(pos) , attrs(AttrDefs{}) , dynamicAttrs(DynamicAttrDefs{}) {}; ExprAttrs() - : recursive(false) - , attrs(AttrDefs{}) + : attrs(AttrDefs{}) , dynamicAttrs(DynamicAttrDefs{}) {}; PosIdx getPos() const override diff --git a/src/libexpr/include/nix/expr/symbol-table.hh b/src/libexpr/include/nix/expr/symbol-table.hh index ccee8bee05e..6cba8d21247 100644 --- a/src/libexpr/include/nix/expr/symbol-table.hh +++ b/src/libexpr/include/nix/expr/symbol-table.hh @@ -2,6 +2,7 @@ ///@file #include +#include #include "nix/expr/value.hh" #include "nix/expr/static-string-data.hh" #include "nix/util/chunked-vector.hh" @@ -42,7 +43,7 @@ class Symbol friend class StaticSymbolTable; private: - uint32_t id; + uint32_t id = 0; explicit constexpr Symbol(uint32_t id) noexcept : id(id) @@ -50,10 +51,7 @@ private: } public: - constexpr Symbol() noexcept - : id(0) - { - } + constexpr Symbol() noexcept = default; [[gnu::always_inline]] constexpr explicit operator bool() const noexcept @@ -290,7 +288,7 @@ public: return Symbol(*symbols.insert(SymbolStr::Key{store, s, buffer}).first); } - std::vector resolve(const std::vector & symbols) const + std::vector resolve(std::span symbols) const { std::vector result; result.reserve(symbols.size()); diff --git a/src/libexpr/include/nix/expr/value.hh b/src/libexpr/include/nix/expr/value.hh index 004dcc43f0f..a1fc2ba4016 100644 --- a/src/libexpr/include/nix/expr/value.hh +++ b/src/libexpr/include/nix/expr/value.hh @@ -35,27 +35,27 @@ class BindingsBuilder; * about how this is mapped into the alignment bits to save significant memory. * This also restricts the number of internal types represented with distinct memory layouts. */ -typedef enum { - tUninitialized = 0, +enum class InternalType { + Uninitialized = 0, /* layout: Single/zero field payload */ - tInt = 1, - tBool, - tNull, - tFloat, - tExternal, - tPrimOp, - tAttrs, + Int = 1, + Bool, + Null, + Float, + External, + PrimOp, + Attrs, /* layout: Pair of pointers payload */ - tListSmall, - tPrimOpApp, - tApp, - tThunk, - tLambda, + ListSmall, + PrimOpApp, + App, + Thunk, + Lambda, /* layout: Single untaggable field */ - tListN, - tString, - tPath, -} InternalType; + ListN, + String, + Path, +}; /** * This type abstracts over all actual value types in the language, @@ -396,7 +396,7 @@ struct ValueBase /** * Like FunctionApplicationThunk, but must be a distinct type in order to - * resolve overloads to `tPrimOpApp` instead of `tApp`. + * resolve overloads to `InternalType::PrimOpApp` instead of `InternalType::App`. * This type helps with the efficient implementation of arity>=2 primop calls. */ struct PrimOpApplicationThunk @@ -428,22 +428,22 @@ struct PayloadTypeToInternalType * overload resolution in setStorage. This ensures there's a bijection from * InternalType <-> C++ type. */ -#define NIX_VALUE_STORAGE_FOR_EACH_FIELD(MACRO) \ - MACRO(NixInt, integer, tInt) \ - MACRO(bool, boolean, tBool) \ - MACRO(ValueBase::StringWithContext, string, tString) \ - MACRO(ValueBase::Path, path, tPath) \ - MACRO(ValueBase::Null, null_, tNull) \ - MACRO(Bindings *, attrs, tAttrs) \ - MACRO(ValueBase::List, bigList, tListN) \ - MACRO(ValueBase::SmallList, smallList, tListSmall) \ - MACRO(ValueBase::ClosureThunk, thunk, tThunk) \ - MACRO(ValueBase::FunctionApplicationThunk, app, tApp) \ - MACRO(ValueBase::Lambda, lambda, tLambda) \ - MACRO(PrimOp *, primOp, tPrimOp) \ - MACRO(ValueBase::PrimOpApplicationThunk, primOpApp, tPrimOpApp) \ - MACRO(ExternalValueBase *, external, tExternal) \ - MACRO(NixFloat, fpoint, tFloat) +#define NIX_VALUE_STORAGE_FOR_EACH_FIELD(MACRO) \ + MACRO(NixInt, integer, InternalType::Int) \ + MACRO(bool, boolean, InternalType::Bool) \ + MACRO(ValueBase::StringWithContext, string, InternalType::String) \ + MACRO(ValueBase::Path, path, InternalType::Path) \ + MACRO(ValueBase::Null, null_, InternalType::Null) \ + MACRO(Bindings *, attrs, InternalType::Attrs) \ + MACRO(ValueBase::List, bigList, InternalType::ListN) \ + MACRO(ValueBase::SmallList, smallList, InternalType::ListSmall) \ + MACRO(ValueBase::ClosureThunk, thunk, InternalType::Thunk) \ + MACRO(ValueBase::FunctionApplicationThunk, app, InternalType::App) \ + MACRO(ValueBase::Lambda, lambda, InternalType::Lambda) \ + MACRO(PrimOp *, primOp, InternalType::PrimOp) \ + MACRO(ValueBase::PrimOpApplicationThunk, primOpApp, InternalType::PrimOpApp) \ + MACRO(ExternalValueBase *, external, InternalType::External) \ + MACRO(NixFloat, fpoint, InternalType::Float) #define NIX_VALUE_PAYLOAD_TYPE(T, FIELD_NAME, DISCRIMINATOR) \ template<> \ @@ -484,7 +484,7 @@ protected: }; private: - InternalType internalType = tUninitialized; + InternalType internalType = InternalType::Uninitialized; Payload payload; protected: @@ -568,8 +568,8 @@ class alignas(16) ValueStorage void setPairOfPointersPayload(T * firstPtrField, U * secondPtrField) noexcept { - static_assert(type >= tListSmall && type <= tLambda); + static_assert(type >= InternalType::ListSmall && type <= InternalType::Lambda); { auto firstFieldPayload = std::bit_cast(firstPtrField); assertAligned(firstFieldPayload); @@ -639,7 +639,7 @@ class alignas(16) ValueStorage(secondPtrField); assertAligned(secondFieldPayload); - payload[1] = (type - tListSmall) | secondFieldPayload; + payload[1] = (static_cast(type) - static_cast(InternalType::ListSmall)) | secondFieldPayload; } } @@ -658,7 +658,7 @@ protected: switch (auto pd = getPrimaryDiscriminator()) { case pdUninitialized: /* Discriminator value of zero is used to distinguish uninitialized values. */ - return tUninitialized; + return InternalType::Uninitialized; case pdSingleDWord: /* Payloads that only use up a single double word store the InternalType in the upper bits of the first double word. */ @@ -667,9 +667,10 @@ protected: case pdListN: case pdString: case pdPath: - return static_cast(tListN + (pd - pdListN)); + return static_cast(static_cast(InternalType::ListN) + (pd - pdListN)); case pdPairOfPointers: - return static_cast(tListSmall + (payload[1] & discriminatorMask)); + return static_cast( + static_cast(InternalType::ListSmall) + (payload[1] & discriminatorMask)); [[unlikely]] default: unreachable(); } @@ -749,37 +750,37 @@ protected: void setStorage(NixInt integer) noexcept { - setSingleDWordPayload(integer.value); + setSingleDWordPayload(integer.value); } void setStorage(bool boolean) noexcept { - setSingleDWordPayload(boolean); + setSingleDWordPayload(boolean); } void setStorage(Null path) noexcept { - setSingleDWordPayload(0); + setSingleDWordPayload(0); } void setStorage(NixFloat fpoint) noexcept { - setSingleDWordPayload(std::bit_cast(fpoint)); + setSingleDWordPayload(std::bit_cast(fpoint)); } void setStorage(ExternalValueBase * external) noexcept { - setSingleDWordPayload(std::bit_cast(external)); + setSingleDWordPayload(std::bit_cast(external)); } void setStorage(PrimOp * primOp) noexcept { - setSingleDWordPayload(std::bit_cast(primOp)); + setSingleDWordPayload(std::bit_cast(primOp)); } void setStorage(Bindings * bindings) noexcept { - setSingleDWordPayload(std::bit_cast(bindings)); + setSingleDWordPayload(std::bit_cast(bindings)); } void setStorage(List list) noexcept @@ -1046,12 +1047,12 @@ public: // type() == nThunk inline bool isThunk() const { - return isa(); + return isa(); }; inline bool isApp() const { - return isa(); + return isa(); }; inline bool isBlackhole() const; @@ -1059,17 +1060,17 @@ public: // type() == nFunction inline bool isLambda() const { - return isa(); + return isa(); }; inline bool isPrimOp() const { - return isa(); + return isa(); }; inline bool isPrimOpApp() const { - return isa(); + return isa(); }; /** @@ -1082,33 +1083,33 @@ public: inline ValueType type(bool invalidIsThunk = false) const { switch (getInternalType()) { - case tUninitialized: + case InternalType::Uninitialized: break; - case tInt: + case InternalType::Int: return nInt; - case tBool: + case InternalType::Bool: return nBool; - case tString: + case InternalType::String: return nString; - case tPath: + case InternalType::Path: return nPath; - case tNull: + case InternalType::Null: return nNull; - case tAttrs: + case InternalType::Attrs: return nAttrs; - case tListSmall: - case tListN: + case InternalType::ListSmall: + case InternalType::ListN: return nList; - case tLambda: - case tPrimOp: - case tPrimOpApp: + case InternalType::Lambda: + case InternalType::PrimOp: + case InternalType::PrimOpApp: return nFunction; - case tExternal: + case InternalType::External: return nExternal; - case tFloat: + case InternalType::Float: return nFloat; - case tThunk: - case tApp: + case InternalType::Thunk: + case InternalType::App: return nThunk; } if (invalidIsThunk) @@ -1124,7 +1125,7 @@ public: */ inline bool isValid() const noexcept { - return !isa(); + return !isa(); } inline void mkInt(NixInt::Inner n) noexcept @@ -1215,7 +1216,7 @@ public: } /** - * For a `tPrimOpApp` value, get the original `PrimOp` value. + * For a `InternalType::PrimOpApp` value, get the original `PrimOp` value. */ const PrimOp * primOpAppPrimOp() const; @@ -1231,17 +1232,18 @@ public: bool isList() const noexcept { - return isa(); + return isa(); } ListView listView() const noexcept { - return isa() ? ListView(getStorage()) : ListView(getStorage()); + return isa() ? ListView(getStorage()) : ListView(getStorage()); } size_t listSize() const noexcept { - return isa() ? (getStorage()[1] == nullptr ? 1 : 2) : getStorage().size; + return isa() ? (getStorage()[1] == nullptr ? 1 : 2) + : getStorage().size; } PosIdx determinePos(const PosIdx pos) const; diff --git a/src/libexpr/json-to-value.cc b/src/libexpr/json-to-value.cc index 4a68308c641..284726d6c54 100644 --- a/src/libexpr/json-to-value.cc +++ b/src/libexpr/json-to-value.cc @@ -57,8 +57,8 @@ class JSONSax : nlohmann::json_sax std::unique_ptr resolve(EvalState & state) override { auto attrs2 = state.buildBindings(attrs.size()); - for (auto & i : attrs) - attrs2.insert(i.first, i.second); + for (auto & [name, value] : attrs) + attrs2.insert(name, value); parent->value(state).mkAttrs(attrs2); return std::move(parent); } diff --git a/src/libexpr/nixexpr.cc b/src/libexpr/nixexpr.cc index fc8c71b07d9..05e54f643de 100644 --- a/src/libexpr/nixexpr.cc +++ b/src/libexpr/nixexpr.cc @@ -5,6 +5,7 @@ #include "nix/expr/print.hh" #include +#include #include #include "nix/util/strings-inline.hh" @@ -78,7 +79,7 @@ void ExprAttrs::showBindings(const SymbolTable & symbols, std::ostream & str) co std::vector sorted; for (auto & i : *attrs) sorted.push_back(&i); - std::sort(sorted.begin(), sorted.end(), [&](Attr a, Attr b) { + std::ranges::sort(sorted, [&](Attr a, Attr b) { std::string_view sa = symbols[a->first], sb = symbols[b->first]; return sa < sb; }); diff --git a/src/libexpr/primops.cc b/src/libexpr/primops.cc index 83d3f667f2e..3fab57529d6 100644 --- a/src/libexpr/primops.cc +++ b/src/libexpr/primops.cc @@ -29,6 +29,7 @@ #include #include +#include #include #include @@ -928,7 +929,7 @@ static RegisterPrimOp primop_break( if (state.canDebug()) { auto error = Error( ErrorInfo{ - .level = lvlInfo, + .level = Verbosity::Info, .msg = HintFmt("breakpoint reached"), .pos = state.positions[pos], }); @@ -1278,7 +1279,7 @@ static void prim_warn(EvalState & state, const PosIdx pos, Value ** args, Value BaseError msg(std::string{msgStr}); msg.atPos(state.positions[pos]); auto info = msg.info(); - info.level = lvlWarn; + info.level = Verbosity::Warn; info.isFromExpr = true; logWarning(info); } @@ -1781,7 +1782,7 @@ static void derivationStrictInternal(EvalState & state, std::string_view drvName auto drvPath = writeDerivation(*state.store, drv, state.repair); auto drvPathS = state.store->printStorePath(drvPath); - printMsg(lvlChatty, "instantiated '%1%' -> '%2%'", drvName, drvPathS); + printMsg(Verbosity::Chatty, "instantiated '%1%' -> '%2%'", drvName, drvPathS); /* Optimisation, but required in read-only mode! because in that case we don't actually write store derivations, so we can't @@ -2974,7 +2975,7 @@ static void prim_attrNames(EvalState & state, const PosIdx pos, Value ** args, V for (const auto & [n, i] : enumerate(*args[0]->attrs())) list[n] = Value::toPtr(state.symbols[i.name]); - std::sort(list.begin(), list.end(), [](Value * v1, Value * v2) { return v1->string_view() < v2->string_view(); }); + std::ranges::sort(list, [](Value * v1, Value * v2) { return v1->string_view() < v2->string_view(); }); v.mkList(list); } @@ -3001,7 +3002,7 @@ static void prim_attrValues(EvalState & state, const PosIdx pos, Value ** args, for (const auto & [n, i] : enumerate(*args[0]->attrs())) list[n] = (Value *) &i; - std::sort(list.begin(), list.end(), [&](Value * v1, Value * v2) { + std::ranges::sort(list, [&](Value * v1, Value * v2) { std::string_view s1 = state.symbols[((Attr *) v1)->name], s2 = state.symbols[((Attr *) v2)->name]; return s1 < s2; }); @@ -4107,11 +4108,11 @@ static void prim_groupBy(EvalState & state, const PosIdx pos, Value ** args, Val auto attrs2 = state.buildBindings(attrs.size()); - for (auto & i : attrs) { - auto size = i.second.size(); + for (auto & [name, values] : attrs) { + auto size = values.size(); auto list = state.buildList(size); - memcpy(list.elems, i.second.data(), sizeof(Value *) * size); - attrs2.alloc(i.first).mkList(list); + memcpy(list.elems, values.data(), sizeof(Value *) * size); + attrs2.alloc(name).mkList(list); } v.mkAttrs(attrs2.alreadySorted()); diff --git a/src/libexpr/primops/context.cc b/src/libexpr/primops/context.cc index 70c13e2985b..2065c7adf87 100644 --- a/src/libexpr/primops/context.cc +++ b/src/libexpr/primops/context.cc @@ -209,19 +209,19 @@ static void prim_getContext(EvalState & state, const PosIdx pos, Value ** args, auto sPath = state.symbols.create("path"); auto sAllOutputs = state.symbols.create("allOutputs"); - for (const auto & info : contextInfos) { + for (const auto & [storePath, ctxInfo] : contextInfos) { auto infoAttrs = state.buildBindings(3); - if (info.second.path) + if (ctxInfo.path) infoAttrs.alloc(sPath).mkBool(true); - if (info.second.allOutputs) + if (ctxInfo.allOutputs) infoAttrs.alloc(sAllOutputs).mkBool(true); - if (!info.second.outputs.empty()) { - auto list = state.buildList(info.second.outputs.size()); - for (const auto & [i, output] : enumerate(info.second.outputs)) + if (!ctxInfo.outputs.empty()) { + auto list = state.buildList(ctxInfo.outputs.size()); + for (const auto & [i, output] : enumerate(ctxInfo.outputs)) (list[i] = state.allocValue())->mkString(output, state.mem); infoAttrs.alloc(state.s.outputs).mkList(list); } - attrs.alloc(state.store->printStorePath(info.first)).mkAttrs(infoAttrs); + attrs.alloc(state.store->printStorePath(storePath)).mkAttrs(infoAttrs); } v.mkAttrs(attrs); diff --git a/src/libexpr/primops/fromTOML.cc b/src/libexpr/primops/fromTOML.cc index 562ff3d1497..77d9c47d2ee 100644 --- a/src/libexpr/primops/fromTOML.cc +++ b/src/libexpr/primops/fromTOML.cc @@ -99,9 +99,9 @@ static void prim_fromTOML(EvalState & state, const PosIdx pos, Value ** args, Va auto table = toml::get(t); auto attrs = state.buildBindings(table.size()); - for (auto & elem : table) { - forceNoNullByte(elem.first); - self(attrs.alloc(elem.first), elem.second); + for (auto & [key, val] : table) { + forceNoNullByte(key); + self(attrs.alloc(key), val); } v.mkAttrs(attrs); diff --git a/src/libexpr/print.cc b/src/libexpr/print.cc index 4776be03385..5320b75b861 100644 --- a/src/libexpr/print.cc +++ b/src/libexpr/print.cc @@ -1,4 +1,5 @@ #include +#include #include #include "nix/expr/print.hh" @@ -346,15 +347,15 @@ class Printer sorted.emplace_back(std::pair(state.symbols[i.name], i.value)); if (options.maxAttrs == std::numeric_limits::max()) - std::sort(sorted.begin(), sorted.end()); + std::ranges::sort(sorted); else - std::sort(sorted.begin(), sorted.end(), ImportantFirstAttrNameCmp()); + std::ranges::sort(sorted, ImportantFirstAttrNameCmp()); auto prettyPrint = shouldPrettyPrintAttrs(sorted); size_t currentAttrsPrinted = 0; - for (auto & i : sorted) { + for (auto & [name, value] : sorted) { printSpace(prettyPrint); if (totalAttrsPrinted >= options.maxAttrs) { @@ -362,9 +363,9 @@ class Printer break; } - printAttributeName(output, i.first); + printAttributeName(output, name); output << " = "; - print(*i.second, depth + 1); + print(*value, depth + 1); output << ";"; totalAttrsPrinted++; currentAttrsPrinted++; diff --git a/src/libfetchers/attrs.cc b/src/libfetchers/attrs.cc index 841808bd16a..efc7c2845cc 100644 --- a/src/libfetchers/attrs.cc +++ b/src/libfetchers/attrs.cc @@ -26,13 +26,13 @@ Attrs jsonToAttrs(const nlohmann::json & json) nlohmann::json attrsToJSON(const Attrs & attrs) { nlohmann::json json; - for (auto & attr : attrs) { - if (auto v = std::get_if(&attr.second)) { - json[attr.first] = *v; - } else if (auto v = std::get_if(&attr.second)) { - json[attr.first] = *v; - } else if (auto v = std::get_if>(&attr.second)) { - json[attr.first] = v->t; + for (auto & [name, value] : attrs) { + if (auto v = std::get_if(&value)) { + json[name] = *v; + } else if (auto v = std::get_if(&value)) { + json[name] = *v; + } else if (auto v = std::get_if>(&value)) { + json[name] = v->t; } else unreachable(); } @@ -96,13 +96,13 @@ bool getBoolAttr(const Attrs & attrs, const std::string & name) StringMap attrsToQuery(const Attrs & attrs) { StringMap query; - for (auto & attr : attrs) { - if (auto v = std::get_if(&attr.second)) { - query.insert_or_assign(attr.first, fmt("%d", *v)); - } else if (auto v = std::get_if(&attr.second)) { - query.insert_or_assign(attr.first, *v); - } else if (auto v = std::get_if>(&attr.second)) { - query.insert_or_assign(attr.first, v->t ? "1" : "0"); + for (auto & [name, value] : attrs) { + if (auto v = std::get_if(&value)) { + query.insert_or_assign(name, fmt("%d", *v)); + } else if (auto v = std::get_if(&value)) { + query.insert_or_assign(name, *v); + } else if (auto v = std::get_if>(&value)) { + query.insert_or_assign(name, v->t ? "1" : "0"); } else unreachable(); } diff --git a/src/libfetchers/cache.cc b/src/libfetchers/cache.cc index 67361c7657d..756bddcf487 100644 --- a/src/libfetchers/cache.cc +++ b/src/libfetchers/cache.cc @@ -53,9 +53,8 @@ struct CacheImpl : Cache void upsert(const Key & key, const Attrs & value) override { - _state.lock() - ->upsert.use()(key.first)(attrsToJSON(key.second).dump())(attrsToJSON(value).dump())(time(0)) - .exec(); + auto & [domain, attrs] = key; + _state.lock()->upsert.use()(domain)(attrsToJSON(attrs).dump())(attrsToJSON(value).dump())(time(0)).exec(); } std::optional lookup(const Key & key) override @@ -67,30 +66,32 @@ struct CacheImpl : Cache std::optional lookupWithTTL(const Key & key) override { + auto & [domain, attrs] = key; if (auto res = lookupExpired(key)) { if (!res->expired) return std::move(res->value); - debug("ignoring expired cache entry '%s:%s'", key.first, attrsToJSON(key.second).dump()); + debug("ignoring expired cache entry '%s:%s'", domain, attrsToJSON(attrs).dump()); } return {}; } std::optional lookupExpired(const Key & key) override { + auto & [domain, attrs] = key; auto state(_state.lock()); - auto keyJSON = attrsToJSON(key.second).dump(); + auto keyJSON = attrsToJSON(attrs).dump(); - auto stmt(state->lookup.use()(key.first)(keyJSON)); + auto stmt(state->lookup.use()(domain)(keyJSON)); if (!stmt.next()) { - debug("did not find cache entry for '%s:%s'", key.first, keyJSON); + debug("did not find cache entry for '%s:%s'", domain, keyJSON); return {}; } auto valueJSON = stmt.getStr(0); auto timestamp = stmt.getInt(1); - debug("using cache entry '%s:%s' -> '%s'", key.first, keyJSON, valueJSON); + debug("using cache entry '%s:%s' -> '%s'", domain, keyJSON, valueJSON); return Result{ .expired = settings.tarballTtl.get() == 0 || timestamp + settings.tarballTtl < time(0), diff --git a/src/libfetchers/fetch-to-store.cc b/src/libfetchers/fetch-to-store.cc index b1e8b9d72bb..521004bf3b3 100644 --- a/src/libfetchers/fetch-to-store.cc +++ b/src/libfetchers/fetch-to-store.cc @@ -47,8 +47,8 @@ StorePath fetchToStore( Activity act( *logger, - lvlChatty, - actUnknown, + Verbosity::Chatty, + ActivityType::Unknown, fmt(mode == FetchMode::DryRun ? "hashing '%s'" : "copying '%s' to the store", path)); auto filter2 = filter ? *filter : defaultPathFilter; diff --git a/src/libfetchers/fetchers.cc b/src/libfetchers/fetchers.cc index 7e091ef1071..154cbad73f5 100644 --- a/src/libfetchers/fetchers.cc +++ b/src/libfetchers/fetchers.cc @@ -236,12 +236,12 @@ void Input::checkLocks(Input specified, Input & result) if (auto prevNarHash = specified.getNarHash()) specified.attrs.insert_or_assign("narHash", prevNarHash->to_string(HashFormat::SRI, true)); - for (auto & field : specified.attrs) { - auto field2 = result.attrs.find(field.first); - if (field2 != result.attrs.end() && field.second != field2->second) + for (auto & [fieldName, fieldValue] : specified.attrs) { + auto field2 = result.attrs.find(fieldName); + if (field2 != result.attrs.end() && fieldValue != field2->second) throw Error( "mismatch in field '%s' of input '%s', got '%s'", - field.first, + fieldName, attrsToJSON(specified.attrs), attrsToJSON(result.attrs)); } @@ -424,9 +424,7 @@ std::optional Input::getNarHash() const std::optional Input::getRef() const { - if (auto s = maybeGetStrAttr(attrs, "ref")) - return *s; - return {}; + return maybeGetStrAttr(attrs, "ref"); } std::optional Input::getRev() const @@ -448,16 +446,12 @@ std::optional Input::getRev() const std::optional Input::getRevCount() const { - if (auto n = maybeGetIntAttr(attrs, "revCount")) - return *n; - return {}; + return maybeGetIntAttr(attrs, "revCount"); } std::optional Input::getLastModified() const { - if (auto n = maybeGetIntAttr(attrs, "lastModified")) - return *n; - return {}; + return maybeGetIntAttr(attrs, "lastModified"); } ParsedURL InputScheme::toURL(const Input & input) const @@ -493,7 +487,11 @@ void InputScheme::clone( auto [accessor, input2] = getAccessor(settings, store, input); - Activity act(*logger, lvlTalkative, actUnknown, fmt("copying '%s' to %s...", input2.to_string(), destDir)); + Activity act( + *logger, + Verbosity::Talkative, + ActivityType::Unknown, + fmt("copying '%s' to %s...", input2.to_string(), destDir)); RestoreSink sink(/*startFsync=*/false); sink.dstPath = destDir; diff --git a/src/libfetchers/git-lfs-fetch.cc b/src/libfetchers/git-lfs-fetch.cc index f1982c314e3..d491d70e1e2 100644 --- a/src/libfetchers/git-lfs-fetch.cc +++ b/src/libfetchers/git-lfs-fetch.cc @@ -13,6 +13,7 @@ #include #include +#include namespace nix::lfs { @@ -28,7 +29,7 @@ static void downloadToSink( FileTransferRequest request(parseURL(url)); Headers headers; if (authHeader.has_value()) - headers.push_back({"Authorization", *authHeader}); + headers.emplace_back("Authorization", *authHeader); request.headers = headers; getFileTransfer()->download(std::move(request), sink); @@ -67,11 +68,11 @@ static LfsApiInfo getLfsApi(const ParsedURL & url) hostnameAndUser << url.authority->host; args.push_back(std::move(hostnameAndUser).str()); - args.push_back("--"); - args.push_back("git-lfs-authenticate"); + args.emplace_back("--"); + args.emplace_back("git-lfs-authenticate"); // FIXME %2F encode slashes? Does this command take/accept percent encoding? - args.push_back(url.renderPath(/*encode=*/false)); - args.push_back("download"); + args.emplace_back(url.renderPath(/*encode=*/false)); + args.emplace_back("download"); auto [status, output] = runProgram({.program = "ssh", .args = args}); @@ -160,12 +161,12 @@ static std::optional parseLfsPointer(std::string_view content, std::str debug("Custom extension '%s' found, ignoring", line); } - if (oid.length() != 64 || !std::all_of(oid.begin(), oid.end(), ::isxdigit)) { + if (oid.length() != 64 || !std::ranges::all_of(oid, ::isxdigit)) { debug("Invalid sha256 %s, skipping", oid); return std::nullopt; } - if (size.length() == 0 || !std::all_of(size.begin(), size.end(), ::isdigit)) { + if (size.length() == 0 || !std::ranges::all_of(size, ::isdigit)) { debug("Invalid size %s, skipping", size); return std::nullopt; } @@ -212,9 +213,9 @@ std::vector Fetch::fetchUrls(const std::vector & pointe request.method = HttpMethod::Post; Headers headers; if (authHeader.has_value()) - headers.push_back({"Authorization", *authHeader}); - headers.push_back({"Content-Type", "application/vnd.git-lfs+json"}); - headers.push_back({"Accept", "application/vnd.git-lfs+json"}); + headers.emplace_back("Authorization", *authHeader); + headers.emplace_back("Content-Type", "application/vnd.git-lfs+json"); + headers.emplace_back("Accept", "application/vnd.git-lfs+json"); request.headers = headers; nlohmann::json oidList = pointerToPayload(pointers); nlohmann::json data = {{"operation", "download"}}; @@ -240,7 +241,7 @@ std::vector Fetch::fetchUrls(const std::vector & pointe return objects; } catch (const nlohmann::json::parse_error & e) { - printMsg(lvlTalkative, "Full response: '%1%'", responseString); + printMsg(Verbosity::Talkative, "Full response: '%1%'", responseString); throw Error("response did not parse as json: %s", e.what()); } } diff --git a/src/libfetchers/git-utils.cc b/src/libfetchers/git-utils.cc index 4a7fc3d0d0d..3c7e616aa26 100644 --- a/src/libfetchers/git-utils.cc +++ b/src/libfetchers/git-utils.cc @@ -556,7 +556,7 @@ struct GitRepoImpl : GitRepo, std::enable_shared_from_this static int sidebandProgressCallback(const char * str, int len, void * payload) { auto act = (Activity *) payload; - act->result(resFetchStatus, trim(std::string_view(str, len))); + act->result(ResultType::FetchStatus, trim(std::string_view(str, len))); return getInterrupted() ? -1 : 0; } @@ -564,7 +564,7 @@ struct GitRepoImpl : GitRepo, std::enable_shared_from_this { auto act = (Activity *) payload; act->result( - resFetchStatus, + ResultType::FetchStatus, fmt("%d/%d objects received, %d/%d deltas indexed, %s", stats->received_objects, stats->total_objects, @@ -576,7 +576,7 @@ struct GitRepoImpl : GitRepo, std::enable_shared_from_this void fetch(const std::string & url, const std::string & refspec, bool shallow) override { - Activity act(*logger, lvlTalkative, actFetchTree, fmt("fetching Git repository '%s'", url)); + Activity act(*logger, Verbosity::Talkative, ActivityType::FetchTree, fmt("fetching Git repository '%s'", url)); // TODO: implement git-credential helper support (preferably via libgit2, which as of 2024-01 does not support // that) diff --git a/src/libfetchers/git.cc b/src/libfetchers/git.cc index 75e3f121481..303b616f8c3 100644 --- a/src/libfetchers/git.cc +++ b/src/libfetchers/git.cc @@ -443,7 +443,7 @@ struct GitInputScheme : InputScheme args.push_back(repoInfo.locationToArg()); if (auto ref = input.getRef()) { - args.push_back("--branch"); + args.emplace_back("--branch"); args.push_back(*ref); } @@ -724,7 +724,10 @@ struct GitInputScheme : InputScheme return getIntAttr(*revCountAttrs, "revCount"); Activity act( - *logger, lvlChatty, actUnknown, fmt("getting Git revision count of '%s'", repoInfo.locationToArg())); + *logger, + Verbosity::Chatty, + ActivityType::Unknown, + fmt("getting Git revision count of '%s'", repoInfo.locationToArg())); auto revCount = GitRepo::openRepo(repoDir)->getRevCount(rev); diff --git a/src/libfetchers/github.cc b/src/libfetchers/github.cc index cd7ce1b4eec..75e9e5817d4 100644 --- a/src/libfetchers/github.cc +++ b/src/libfetchers/github.cc @@ -312,7 +312,10 @@ struct GitArchiveInputScheme : InputScheme }); auto act = std::make_unique( - *logger, lvlInfo, actUnknown, fmt("unpacking '%s' into the Git cache", input.to_string())); + *logger, + Verbosity::Info, + ActivityType::Unknown, + fmt("unpacking '%s' into the Git cache", input.to_string())); TarArchive archive{*source}; auto tarballCache = settings.getTarballCache(); diff --git a/src/libfetchers/mercurial.cc b/src/libfetchers/mercurial.cc index 87e18133d95..dd571fdc39a 100644 --- a/src/libfetchers/mercurial.cc +++ b/src/libfetchers/mercurial.cc @@ -286,7 +286,11 @@ struct MercurialInputScheme : InputScheme && runProgram(hgOptions({"log", "-R", cacheDir, "-r", input.getRev()->gitRev(), "--template", "1"})) .second == "1")) { - Activity act(*logger, lvlTalkative, actUnknown, fmt("fetching Mercurial repository '%s'", actualUrl)); + Activity act( + *logger, + Verbosity::Talkative, + ActivityType::Unknown, + fmt("fetching Mercurial repository '%s'", actualUrl)); if (pathExists(cacheDir)) { try { diff --git a/src/libfetchers/path.cc b/src/libfetchers/path.cc index 7f48ce07bb9..79e84b4f068 100644 --- a/src/libfetchers/path.cc +++ b/src/libfetchers/path.cc @@ -154,7 +154,7 @@ struct PathInputScheme : InputScheme time_t mtime = 0; if (!storePath || storePath->name() != "source" || !store.isValidPath(*storePath)) { - Activity act(*logger, lvlTalkative, actUnknown, fmt("copying %s to the store", absPath)); + Activity act(*logger, Verbosity::Talkative, ActivityType::Unknown, fmt("copying %s to the store", absPath)); // FIXME: try to substitute storePath. auto src = sinkToSource( [&](Sink & sink) { mtime = dumpPathAndGetMtime(absPath.string(), sink, defaultPathFilter); }); diff --git a/src/libfetchers/registry.cc b/src/libfetchers/registry.cc index cb360f03c9e..1f8d65f1e1c 100644 --- a/src/libfetchers/registry.cc +++ b/src/libfetchers/registry.cc @@ -85,9 +85,7 @@ void Registry::add(const Input & from, const Input & to, const Attrs & extraAttr void Registry::remove(const Input & input) { - entries.erase( - std::remove_if(entries.begin(), entries.end(), [&](const Entry & entry) { return entry.from == input; }), - entries.end()); + std::erase_if(entries, [&](const Entry & entry) { return entry.from == input; }); } static Path getSystemRegistryPath() diff --git a/src/libfetchers/tarball.cc b/src/libfetchers/tarball.cc index b1ebd749df6..e11b69f9f23 100644 --- a/src/libfetchers/tarball.cc +++ b/src/libfetchers/tarball.cc @@ -158,7 +158,8 @@ static DownloadTarballResult downloadTarball_( // TODO: fall back to cached value if download fails. - auto act = std::make_unique(*logger, lvlInfo, actUnknown, fmt("unpacking '%s' into the Git cache", url)); + auto act = std::make_unique( + *logger, Verbosity::Info, ActivityType::Unknown, fmt("unpacking '%s' into the Git cache", url)); AutoDelete cleanupTemp; diff --git a/src/libflake/flake.cc b/src/libflake/flake.cc index 9f7476bd0e2..e57ee07db40 100644 --- a/src/libflake/flake.cc +++ b/src/libflake/flake.cc @@ -356,10 +356,10 @@ static FlakeRef applySelfAttrs(const FlakeRef & ref, const Flake & flake) StringSet allowedAttrs{"submodules", "lfs"}; - for (auto & attr : flake.selfAttrs) { - if (!allowedAttrs.contains(attr.first)) - throw Error("flake 'self' attribute '%s' is not supported", attr.first); - newRef.input.attrs.insert_or_assign(attr.first, attr.second); + for (auto & [attrName, attrValue] : flake.selfAttrs) { + if (!allowedAttrs.contains(attrName)) + throw Error("flake 'self' attribute '%s' is not supported", attrName); + newRef.input.attrs.insert_or_assign(attrName, attrValue); } return newRef; @@ -456,18 +456,18 @@ lockFlake(const Settings & settings, EvalState & state, const FlakeRef & topRef, std::set overridesUsed, updatesUsed; std::map, SourcePath> nodePaths; - for (auto & i : lockFlags.inputOverrides) { + for (auto & [inputPath, inputRef] : lockFlags.inputOverrides) { overrides.emplace( - i.first, + inputPath, OverrideTarget{ - .input = FlakeInput{.ref = i.second}, + .input = FlakeInput{.ref = inputRef}, /* Note: any relative overrides (e.g. `--override-input B/C "path:./foo/bar"`) are interpreted relative to the top-level flake. */ .sourcePath = flake.path, }); - explicitCliOverrides.insert(i.first); + explicitCliOverrides.insert(inputPath); } LockFile newLockFile; diff --git a/src/libflake/lockfile.cc b/src/libflake/lockfile.cc index f2914feab78..6c5cbf67254 100644 --- a/src/libflake/lockfile.cc +++ b/src/libflake/lockfile.cc @@ -57,8 +57,8 @@ getFlakeRef(const fetchers::Settings & fetchSettings, const nlohmann::json & jso if (info) { auto j = json.find(info); if (j != json.end()) { - for (auto k : fetchers::jsonToAttrs(*j)) - attrs.insert_or_assign(k.first, k.second); + for (auto [name, value] : fetchers::jsonToAttrs(*j)) + attrs.insert_or_assign(name, value); } } return FlakeRef::fromAttrs(fetchSettings, attrs); @@ -213,14 +213,14 @@ std::pair LockFile::toJSON() const if (!node->inputs.empty()) { auto inputs = nlohmann::json::object(); - for (auto & i : node->inputs) { - if (auto child = std::get_if<0>(&i.second)) { - inputs[i.first] = dumpNode(i.first, *child); - } else if (auto follows = std::get_if<1>(&i.second)) { + for (auto & [inputName, inputValue] : node->inputs) { + if (auto child = std::get_if<0>(&inputValue)) { + inputs[inputName] = dumpNode(inputName, *child); + } else if (auto follows = std::get_if<1>(&inputValue)) { auto arr = nlohmann::json::array(); for (auto & x : *follows) arr.push_back(x); - inputs[i.first] = std::move(arr); + inputs[inputName] = std::move(arr); } } n["inputs"] = std::move(inputs); diff --git a/src/libmain/common-args.cc b/src/libmain/common-args.cc index 6055ec0e752..f9edd81f2bb 100644 --- a/src/libmain/common-args.cc +++ b/src/libmain/common-args.cc @@ -19,23 +19,21 @@ MixCommonArgs::MixCommonArgs(const std::string & programName) .shortName = 'v', .description = "Increase the logging verbosity level.", .category = loggingCategory, - .handler = {[]() { - verbosity = (Verbosity) std::min>(verbosity + 1, lvlVomit); - }}, + .handler = {[]() { ++verbosity; }}, }); addFlag({ .longName = "quiet", .description = "Decrease the logging verbosity level.", .category = loggingCategory, - .handler = {[]() { verbosity = verbosity > lvlError ? (Verbosity) (verbosity - 1) : lvlError; }}, + .handler = {[]() { --verbosity; }}, }); addFlag({ .longName = "debug", .description = "Set the logging verbosity level to 'debug'.", .category = loggingCategory, - .handler = {[]() { verbosity = lvlDebug; }}, + .handler = {[]() { verbosity = Verbosity::Debug; }}, }); addFlag({ @@ -56,9 +54,9 @@ MixCommonArgs::MixCommonArgs(const std::string & programName) if (index == 0) { std::map settings; globalConfig.getSettings(settings); - for (auto & s : settings) - if (hasPrefix(s.first, prefix)) - completions.add(s.first, fmt("Set the `%s` setting.", s.first)); + for (auto & [name, _] : settings) + if (hasPrefix(name, prefix)) + completions.add(name, fmt("Set the `%s` setting.", name)); } }, }); diff --git a/src/libmain/include/nix/main/shared.hh b/src/libmain/include/nix/main/shared.hh index 43069ba82bd..9fc3c4e1537 100644 --- a/src/libmain/include/nix/main/shared.hh +++ b/src/libmain/include/nix/main/shared.hh @@ -39,9 +39,9 @@ void printGCWarning(); class Store; struct MissingPaths; -void printMissing(ref store, const std::vector & paths, Verbosity lvl = lvlInfo); +void printMissing(ref store, const std::vector & paths, Verbosity lvl = Verbosity::Info); -void printMissing(ref store, const MissingPaths & missing, Verbosity lvl = lvlInfo); +void printMissing(ref store, const MissingPaths & missing, Verbosity lvl = Verbosity::Info); std::string getArg(const std::string & opt, Strings::iterator & i, const Strings::iterator & end); diff --git a/src/libmain/progress-bar.cc b/src/libmain/progress-bar.cc index a973102f950..3abd3b07ff6 100644 --- a/src/libmain/progress-bar.cc +++ b/src/libmain/progress-bar.cc @@ -16,14 +16,14 @@ namespace nix { static std::string_view getS(const std::vector & fields, size_t n) { assert(n < fields.size()); - assert(fields[n].type == Logger::Field::tString); + assert(fields[n].type == Logger::Field::Type::String); return fields[n].s; } static uint64_t getI(const std::vector & fields, size_t n) { assert(n < fields.size()); - assert(fields[n].type == Logger::Field::tInt); + assert(fields[n].type == Logger::Field::Type::Int); return fields[n].i; } @@ -41,7 +41,7 @@ class ProgressBar : public Logger struct ActInfo { std::string s, lastLine, phase; - ActivityType type = actUnknown; + ActivityType type = ActivityType::Unknown; uint64_t done = 0; uint64_t expected = 0; uint64_t running = 0; @@ -150,7 +150,8 @@ class ProgressBar : public Logger { auto state(state_.lock()); if (state->suspensions == 0) { - log(lvlError, "nix::ProgressBar: resume() called without a matching preceding pause(). This is a bug."); + log(Verbosity::Error, + "nix::ProgressBar: resume() called without a matching preceding pause(). This is a bug."); return; } else { state->suspensions--; @@ -206,7 +207,7 @@ class ProgressBar : public Logger { auto state(state_.lock()); - if (lvl <= verbosity && !s.empty() && type != actBuildWaiting) + if (lvl <= verbosity && !s.empty() && type != ActivityType::BuildWaiting) log(*state, lvl, s + "..."); state->activities.emplace_back( @@ -215,7 +216,7 @@ class ProgressBar : public Logger state->its.emplace(act, i); state->activitiesByType[type].its.emplace(act, i); - if (type == actBuild) { + if (type == ActivityType::Build) { std::string name(storePathToName(getS(fields, 0))); if (hasSuffix(name, ".drv")) name = name.substr(0, name.size() - 4); @@ -232,7 +233,7 @@ class ProgressBar : public Logger i->name = DrvName(name).name; } - if (type == actSubstitute) { + if (type == ActivityType::Substitute) { auto name = storePathToName(getS(fields, 0)); auto sub = getS(fields, 1); i->s = @@ -242,7 +243,7 @@ class ProgressBar : public Logger sub); } - if (type == actPostBuildHook) { + if (type == ActivityType::PostBuildHook) { auto name = storePathToName(getS(fields, 0)); if (hasSuffix(name, ".drv")) name = name.substr(0, name.size() - 4); @@ -250,14 +251,14 @@ class ProgressBar : public Logger i->name = DrvName(name).name; } - if (type == actQueryPathInfo) { + if (type == ActivityType::QueryPathInfo) { auto name = storePathToName(getS(fields, 0)); i->s = fmt("querying " ANSI_BOLD "%s" ANSI_NORMAL " on %s", name, getS(fields, 1)); } - if ((type == actFileTransfer && hasAncestor(*state, actCopyPath, parent)) - || (type == actFileTransfer && hasAncestor(*state, actQueryPathInfo, parent)) - || (type == actCopyPath && hasAncestor(*state, actSubstitute, parent))) + if ((type == ActivityType::FileTransfer && hasAncestor(*state, ActivityType::CopyPath, parent)) + || (type == ActivityType::FileTransfer && hasAncestor(*state, ActivityType::QueryPathInfo, parent)) + || (type == ActivityType::CopyPath && hasAncestor(*state, ActivityType::Substitute, parent))) i->visible = false; update(*state); @@ -289,8 +290,8 @@ class ProgressBar : public Logger actByType.done += i->second->done; actByType.failed += i->second->failed; - for (auto & j : i->second->expectedByType) - state->activitiesByType[j.first].expected -= j.second; + for (auto & [type, expected] : i->second->expectedByType) + state->activitiesByType[type].expected -= expected; actByType.its.erase(act); state->activities.erase(i->second); @@ -304,23 +305,25 @@ class ProgressBar : public Logger { auto state(state_.lock()); - if (type == resFileLinked) { + if (type == ResultType::FileLinked) { state->filesLinked++; state->bytesLinked += getI(fields, 0); update(*state); } - else if (type == resBuildLogLine || type == resPostBuildLogLine) { + else if (type == ResultType::BuildLogLine || type == ResultType::PostBuildLogLine) { auto lastLine = chomp(getS(fields, 0)); auto i = state->its.find(act); assert(i != state->its.end()); ActInfo info = *i->second; if (printBuildLogs) { auto suffix = "> "; - if (type == resPostBuildLogLine) { + if (type == ResultType::PostBuildLogLine) { suffix = " (post)> "; } - log(*state, lvlInfo, ANSI_FAINT + info.name.value_or("unnamed") + suffix + ANSI_NORMAL + lastLine); + log(*state, + Verbosity::Info, + ANSI_FAINT + info.name.value_or("unnamed") + suffix + ANSI_NORMAL + lastLine); } else { state->activities.erase(i->second); info.lastLine = lastLine; @@ -330,24 +333,24 @@ class ProgressBar : public Logger } } - else if (type == resUntrustedPath) { + else if (type == ResultType::UntrustedPath) { state->untrustedPaths++; update(*state); } - else if (type == resCorruptedPath) { + else if (type == ResultType::CorruptedPath) { state->corruptedPaths++; update(*state); } - else if (type == resSetPhase) { + else if (type == ResultType::SetPhase) { auto i = state->its.find(act); assert(i != state->its.end()); i->second->phase = getS(fields, 0); update(*state); } - else if (type == resProgress) { + else if (type == ResultType::Progress) { auto i = state->its.find(act); assert(i != state->its.end()); ActInfo & actInfo = *i->second; @@ -358,7 +361,7 @@ class ProgressBar : public Logger update(*state); } - else if (type == resSetExpected) { + else if (type == ResultType::SetExpected) { auto i = state->its.find(act); assert(i != state->its.end()); ActInfo & actInfo = *i->second; @@ -370,7 +373,7 @@ class ProgressBar : public Logger update(*state); } - else if (type == resFetchStatus) { + else if (type == ResultType::FetchStatus) { auto i = state->its.find(act); assert(i != state->its.end()); ActInfo & actInfo = *i->second; @@ -474,11 +477,11 @@ class ProgressBar : public Logger ActivityType type, const std::string & itemFmt, const std::string & numberFmt = "%d", double unit = 1) { auto & act = state.activitiesByType[type]; uint64_t done = act.done, expected = act.done, running = 0, failed = act.failed; - for (auto & j : act.its) { - done += j.second->done; - expected += j.second->expected; - running += j.second->running; - failed += j.second->failed; + for (auto & [_, info] : act.its) { + done += info->done; + expected += info->expected; + running += info->running; + failed += info->failed; } expected = std::max(expected, act.expected); @@ -518,11 +521,11 @@ class ProgressBar : public Logger auto renderSizeActivity = [&] [[nodiscard]] (ActivityType type, const std::string & itemFmt = "%s") { auto & act = state.activitiesByType[type]; uint64_t done = act.done, expected = act.done, running = 0, failed = act.failed; - for (auto & j : act.its) { - done += j.second->done; - expected += j.second->expected; - running += j.second->running; - failed += j.second->failed; + for (auto & [_, info] : act.its) { + done += info->done; + expected += info->expected; + running += info->running; + failed += info->failed; } expected = std::max(expected, act.expected); @@ -587,10 +590,10 @@ class ProgressBar : public Logger maybeAppendToResult(renderActivity(type, itemFmt, numberFmt, unit)); }; - showActivity(actBuilds, "%s built"); + showActivity(ActivityType::Builds, "%s built"); - auto s1 = renderActivity(actCopyPaths, "%s copied"); - auto s2 = renderSizeActivity(actCopyPath); + auto s1 = renderActivity(ActivityType::CopyPaths, "%s copied"); + auto s2 = renderSizeActivity(ActivityType::CopyPath); if (!s1.empty() || !s2.empty()) { if (!res.empty()) @@ -606,10 +609,10 @@ class ProgressBar : public Logger } } - maybeAppendToResult(renderSizeActivity(actFileTransfer, "%s DL")); + maybeAppendToResult(renderSizeActivity(ActivityType::FileTransfer, "%s DL")); { - auto s = renderActivity(actOptimiseStore, "%s paths optimised"); + auto s = renderActivity(ActivityType::OptimiseStore, "%s paths optimised"); if (s != "") { s += fmt(", %s / %d inodes freed", renderSize(state.bytesLinked), state.filesLinked); if (!res.empty()) @@ -619,7 +622,7 @@ class ProgressBar : public Logger } // FIXME: don't show "done" paths in green. - showActivity(actVerifyPaths, "%s paths verified"); + showActivity(ActivityType::VerifyPaths, "%s paths verified"); if (state.corruptedPaths) { if (!res.empty()) diff --git a/src/libmain/shared.cc b/src/libmain/shared.cc index 19733fb3ec3..e8c1474a211 100644 --- a/src/libmain/shared.cc +++ b/src/libmain/shared.cc @@ -10,6 +10,7 @@ #include #include +#include #include #include @@ -79,17 +80,15 @@ void printMissing(ref store, const MissingPaths & missing, Verbosity lvl) renderSize(missing.downloadSize), renderSize(missing.narSize)); } - std::vector willSubstituteSorted = {}; - std::for_each(missing.willSubstitute.begin(), missing.willSubstitute.end(), [&](const StorePath & p) { + std::vector willSubstituteSorted; + for (const auto & p : missing.willSubstitute) willSubstituteSorted.push_back(&p); + std::ranges::sort(willSubstituteSorted, [](const StorePath * lhs, const StorePath * rhs) { + if (lhs->name() == rhs->name()) + return lhs->to_string() < rhs->to_string(); + else + return lhs->name() < rhs->name(); }); - std::sort( - willSubstituteSorted.begin(), willSubstituteSorted.end(), [](const StorePath * lhs, const StorePath * rhs) { - if (lhs->name() == rhs->name()) - return lhs->to_string() < rhs->to_string(); - else - return lhs->name() < rhs->name(); - }); for (auto p : willSubstituteSorted) printMsg(lvl, " %s", store->printStorePath(*p)); } @@ -295,7 +294,7 @@ void parseCmdLine( void printVersion(const std::string & programName) { std::cout << fmt("%1% (Nix) %2%", programName, nixVersion) << std::endl; - if (verbosity > lvlInfo) { + if (verbosity > Verbosity::Info) { Strings cfg; #if NIX_USE_BOEHMGC cfg.push_back("gc"); diff --git a/src/libstore-test-support/test-main.cc b/src/libstore-test-support/test-main.cc index 0b9072dc08f..4d2770fd6eb 100644 --- a/src/libstore-test-support/test-main.cc +++ b/src/libstore-test-support/test-main.cc @@ -37,7 +37,7 @@ int testMainForBuidingPre(int argc, char ** argv) #ifdef __APPLE__ // Avoid this error, when already running in a sandbox: // sandbox-exec: sandbox_apply: Operation not permitted - settings.sandboxMode = smDisabled; + settings.sandboxMode = SandboxMode::Disabled; setEnv("_NIX_TEST_NO_SANDBOX", "1"); #endif diff --git a/src/libstore/aws-creds.cc b/src/libstore/aws-creds.cc index dfdd81abbc4..d3f99ba508a 100644 --- a/src/libstore/aws-creds.cc +++ b/src/libstore/aws-creds.cc @@ -81,11 +81,11 @@ class AwsCredentialProviderImpl : public AwsCredentialProvider { // Map Nix's verbosity to AWS CRT log level Aws::Crt::LogLevel logLevel; - if (verbosity >= lvlVomit) { + if (verbosity >= Verbosity::Vomit) { logLevel = Aws::Crt::LogLevel::Trace; - } else if (verbosity >= lvlDebug) { + } else if (verbosity >= Verbosity::Debug) { logLevel = Aws::Crt::LogLevel::Debug; - } else if (verbosity >= lvlChatty) { + } else if (verbosity >= Verbosity::Chatty) { logLevel = Aws::Crt::LogLevel::Info; } else { logLevel = Aws::Crt::LogLevel::Warn; diff --git a/src/libstore/binary-cache-store.cc b/src/libstore/binary-cache-store.cc index e1f1d24c6d7..6a6ccd61fb0 100644 --- a/src/libstore/binary-cache-store.cc +++ b/src/libstore/binary-cache-store.cc @@ -183,7 +183,7 @@ ref BinaryCacheStore::addToStoreCommon( auto duration = std::chrono::duration_cast(now2 - now1).count(); printMsg( - lvlTalkative, + Verbosity::Talkative, "copying path '%1%' (%2% bytes, compressed %3$.1f%% in %4% ms) to binary cache", printStorePath(narInfo->path), info.narSize, @@ -237,7 +237,7 @@ ref BinaryCacheStore::addToStoreCommon( if (fileExists(key)) return; - printMsg(lvlTalkative, "creating debuginfo link from '%s' to '%s'", key, target); + printMsg(Verbosity::Talkative, "creating debuginfo link from '%s' to '%s'", key, target); upsertFile(key, json.dump(), "application/json"); }; @@ -451,8 +451,8 @@ void BinaryCacheStore::queryPathInfoUncached( auto storePathS = printStorePath(storePath); auto act = std::make_shared( *logger, - lvlTalkative, - actQueryPathInfo, + Verbosity::Talkative, + ActivityType::QueryPathInfo, fmt("querying info about '%s' on '%s'", storePathS, uri), Logger::Fields{storePathS, uri}); PushActivity pact(act->id); diff --git a/src/libstore/build/derivation-building-goal.cc b/src/libstore/build/derivation-building-goal.cc index 8221e12c697..120bebed779 100644 --- a/src/libstore/build/derivation-building-goal.cc +++ b/src/libstore/build/derivation-building-goal.cc @@ -269,8 +269,8 @@ Goal::Co DerivationBuildingGoal::tryToBuild() #endif act = std::make_unique( *logger, - lvlInfo, - actBuild, + Verbosity::Info, + ActivityType::Build, msg, Logger::Fields{ worker.store.printStorePath(drvPath), @@ -328,7 +328,10 @@ Goal::Co DerivationBuildingGoal::tryToBuild() if (!outputLocks.lockPaths(lockFiles, "", false)) { Activity act( - *logger, lvlWarn, actBuildWaiting, fmt("waiting for lock on %s", Magenta(showPaths(lockFiles)))); + *logger, + Verbosity::Warn, + ActivityType::BuildWaiting, + fmt("waiting for lock on %s", Magenta(showPaths(lockFiles)))); /* Wait then try locking again, repeat until success (returned boolean is true). */ @@ -375,24 +378,24 @@ Goal::Co DerivationBuildingGoal::tryToBuild() useHook = false; } else { switch (tryBuildHook(initialOutputs, drvOptions)) { - case rpAccept: + case HookReply::Accept: /* Yes, it has started doing so. Wait until we get EOF from the hook. */ useHook = true; break; - case rpPostpone: + case HookReply::Postpone: /* Not now; wait until at least one child finishes or the wake-up timeout expires. */ if (!actLock) actLock = std::make_unique( *logger, - lvlWarn, - actBuildWaiting, + Verbosity::Warn, + ActivityType::BuildWaiting, fmt("waiting for a machine to build '%s'", Magenta(worker.store.printStorePath(drvPath)))); outputLocks.unlock(); co_await waitForAWhile(); continue; - case rpDecline: + case HookReply::Decline: /* We should do it ourselves. Now that we've decided we can't / won't do a remote build, check @@ -649,8 +652,8 @@ Goal::Co DerivationBuildingGoal::tryToBuild() if (!actLock) actLock = std::make_unique( *logger, - lvlWarn, - actBuildWaiting, + Verbosity::Warn, + ActivityType::BuildWaiting, fmt("waiting for a free build user ID for '%s'", Magenta(worker.store.printStorePath(drvPath)))); co_await waitForAWhile(); continue; @@ -738,8 +741,8 @@ static void runPostBuildHook( Activity act( logger, - lvlTalkative, - actPostBuildHook, + Verbosity::Talkative, + ActivityType::PostBuildHook, fmt("running post-build-hook '%s'", settings.postBuildHook), Logger::Fields{store.printStorePath(drvPath)}); PushActivity pact(act.id); @@ -772,7 +775,7 @@ static void runPostBuildHook( void flushLine() { - act.result(resPostBuildLogLine, currentLine); + act.result(ResultType::PostBuildLogLine, currentLine); currentLine.clear(); } @@ -831,12 +834,12 @@ HookReply DerivationBuildingGoal::tryBuildHook( const std::map & initialOutputs, const DerivationOptions & drvOptions) { #ifdef _WIN32 // TODO enable build hook on Windows - return rpDecline; + return HookReply::Decline; #else /* This should use `worker.evalStore`, but per #13179 the build hook doesn't work with eval store anyways. */ if (settings.buildHook.get().empty() || !worker.tryBuildHook || !worker.store.isValidPath(drvPath)) - return rpDecline; + return HookReply::Decline; if (!worker.hook) worker.hook = std::make_unique(); @@ -874,13 +877,13 @@ HookReply DerivationBuildingGoal::tryBuildHook( debug("hook reply is '%1%'", reply); if (reply == "decline") - return rpDecline; + return HookReply::Decline; else if (reply == "decline-permanently") { worker.tryBuildHook = false; worker.hook = 0; - return rpDecline; + return HookReply::Decline; } else if (reply == "postpone") - return rpPostpone; + return HookReply::Postpone; else if (reply != "accept") throw Error("bad hook reply '%s'", reply); @@ -888,7 +891,7 @@ HookReply DerivationBuildingGoal::tryBuildHook( if (e.errNo == EPIPE) { printError("build hook died unexpectedly: %s", chomp(drainFD(worker.hook->fromHook.readSide.get()))); worker.hook = 0; - return rpDecline; + return HookReply::Decline; } else throw; } @@ -932,7 +935,7 @@ HookReply DerivationBuildingGoal::tryBuildHook( fds.insert(hook->builderOut.readSide.get()); worker.childStarted(shared_from_this(), fds, false, false); - return rpAccept; + return HookReply::Accept; #endif } @@ -1042,9 +1045,9 @@ void DerivationBuildingGoal::handleChildOutput(Descriptor fd, std::string_view d if (s && !isWrittenToLog && logSink) { const auto type = (*json)["type"]; const auto fields = (*json)["fields"]; - if (type == resBuildLogLine) { + if (type == ResultType::BuildLogLine) { (*logSink)((fields.size() > 0 ? fields[0].get() : "") + "\n"); - } else if (type == resSetPhase && !fields.is_null()) { + } else if (type == ResultType::SetPhase && !fields.is_null()) { const auto phase = fields[0]; if (!phase.is_null()) { // nixpkgs' stdenv produces lines in the log to signal @@ -1084,7 +1087,7 @@ void DerivationBuildingGoal::flushLine() if (logTail.size() > settings.logLines) logTail.pop_front(); - act->result(resBuildLogLine, currentLogLine); + act->result(ResultType::BuildLogLine, currentLogLine); } currentLogLine = ""; diff --git a/src/libstore/build/derivation-resolution-goal.cc b/src/libstore/build/derivation-resolution-goal.cc index 6cb9702f4f6..e471d64ec9f 100644 --- a/src/libstore/build/derivation-resolution-goal.cc +++ b/src/libstore/build/derivation-resolution-goal.cc @@ -172,8 +172,8 @@ Goal::Co DerivationResolutionGoal::resolveDerivation() worker.store.printStorePath(pathResolved)); act = std::make_unique( *logger, - lvlInfo, - actBuildWaiting, + Verbosity::Info, + ActivityType::BuildWaiting, msg, Logger::Fields{ worker.store.printStorePath(drvPath), diff --git a/src/libstore/build/substitution-goal.cc b/src/libstore/build/substitution-goal.cc index ac18de304b7..f2681d8abe6 100644 --- a/src/libstore/build/substitution-goal.cc +++ b/src/libstore/build/substitution-goal.cc @@ -234,7 +234,7 @@ Goal::Co PathSubstitutionGoal::tryToRun( Activity act( *logger, - actSubstitute, + ActivityType::Substitute, Logger::Fields{worker.store.printStorePath(storePath), sub->config.getHumanReadableURI()}); PushActivity pact(act.id); @@ -288,7 +288,7 @@ Goal::Co PathSubstitutionGoal::tryToRun( worker.markContentsGood(storePath); - printMsg(lvlChatty, "substitution of path '%s' succeeded", worker.store.printStorePath(storePath)); + printMsg(Verbosity::Chatty, "substitution of path '%s' succeeded", worker.store.printStorePath(storePath)); maintainRunningSubstitutions.reset(); diff --git a/src/libstore/build/worker.cc b/src/libstore/build/worker.cc index 3663a2c919f..42aad3df427 100644 --- a/src/libstore/build/worker.cc +++ b/src/libstore/build/worker.cc @@ -16,9 +16,9 @@ namespace nix { Worker::Worker(Store & store, Store & evalStore) - : act(*logger, actRealise) - , actDerivations(*logger, actBuilds) - , actSubstitutions(*logger, actCopyPaths) + : act(*logger, ActivityType::Realise) + , actDerivations(*logger, ActivityType::Builds) + , actSubstitutions(*logger, ActivityType::CopyPaths) , store(store) , evalStore(evalStore) { @@ -383,7 +383,7 @@ void Worker::run(const Goals & _topGoals) void Worker::waitForInput() { - printMsg(lvlVomit, "waiting for children"); + printMsg(Verbosity::Vomit, "waiting for children"); /* Process output from the file descriptors attached to the children, namely log output and output path creation commands. @@ -468,7 +468,7 @@ void Worker::waitForInput() state.iterate( j->channels, [&](Descriptor k, std::string_view data) { - printMsg(lvlVomit, "%1%: read %2% bytes", goal->getName(), data.size()); + printMsg(Verbosity::Vomit, "%1%: read %2% bytes", goal->getName(), data.size()); j->lastOutput = after; goal->handleChildOutput(k, data); }, diff --git a/src/libstore/builtins/buildenv.cc b/src/libstore/builtins/buildenv.cc index 4db37d43a79..8b19d456764 100644 --- a/src/libstore/builtins/buildenv.cc +++ b/src/libstore/builtins/buildenv.cc @@ -7,6 +7,7 @@ #include #include #include +#include namespace nix { @@ -151,7 +152,7 @@ void buildProfile(const Path & out, Packages && pkgs) * user. Process in priority order to reduce unnecessary * symlink/unlink steps. */ - std::sort(pkgs.begin(), pkgs.end(), [](const Package & a, const Package & b) { + std::ranges::sort(pkgs, [](const Package & a, const Package & b) { return a.priority < b.priority || (a.priority == b.priority && a.path < b.path); }); for (const auto & pkg : pkgs) diff --git a/src/libstore/daemon.cc b/src/libstore/daemon.cc index 2a382dca7c0..0f783b4abff 100644 --- a/src/libstore/daemon.cc +++ b/src/libstore/daemon.cc @@ -30,10 +30,10 @@ Sink & operator<<(Sink & sink, const Logger::Fields & fields) { sink << fields.size(); for (auto & f : fields) { - sink << f.type; - if (f.type == Logger::Field::tInt) + sink << static_cast(f.type); + if (f.type == Logger::Field::Type::Int) sink << f.i; - else if (f.type == Logger::Field::tString) + else if (f.type == Logger::Field::Type::String) sink << f.s; else unreachable(); @@ -155,7 +155,8 @@ struct TunnelLogger : public Logger } StringSink buf; - buf << STDERR_START_ACTIVITY << act << lvl << type << s << fields << parent; + buf << STDERR_START_ACTIVITY << act << static_cast(lvl) << static_cast(type) << s << fields + << parent; enqueueMsg(buf.s); } @@ -173,7 +174,7 @@ struct TunnelLogger : public Logger if (GET_PROTOCOL_MINOR(clientVersion) < 20) return; StringSink buf; - buf << STDERR_RESULT << act << type << fields; + buf << STDERR_RESULT << act << static_cast(type) << fields; enqueueMsg(buf.s); } }; @@ -241,9 +242,7 @@ struct ClientSettings settings.buildCores = buildCores; settings.useSubstitutes = useSubstitutes; - for (auto & i : overrides) { - auto & name(i.first); - auto & value(i.second); + for (auto & [name, value] : overrides) { auto setSubstituters = [&](Setting & res) { if (name != res.name && res.aliases.count(name) == 0) @@ -727,8 +726,8 @@ static void performOp( logger->stopWork(); size_t size = 0; - for (auto & i : roots) - size += i.second.size(); + for (auto & [_, links] : roots) + size += links.size(); conn.to << size; @@ -776,7 +775,7 @@ static void performOp( clientSettings.maxBuildJobs = readInt(conn.from); clientSettings.maxSilentTime = readInt(conn.from); readInt(conn.from); // obsolete useBuildHook - clientSettings.verboseBuild = lvlError == (Verbosity) readInt(conn.from); + clientSettings.verboseBuild = Verbosity::Error == (Verbosity) readInt(conn.from); readInt(conn.from); // obsolete logType readInt(conn.from); // obsolete printBuildTrace clientSettings.buildCores = readInt(conn.from); @@ -831,11 +830,11 @@ static void performOp( store->querySubstitutablePathInfos(pathsMap, infos); logger->stopWork(); conn.to << infos.size(); - for (auto & i : infos) { - WorkerProto::write(*store, wconn, i.first); - WorkerProto::write(*store, wconn, i.second.deriver); - WorkerProto::write(*store, wconn, i.second.references); - conn.to << i.second.downloadSize << i.second.narSize; + for (auto & [path, info] : infos) { + WorkerProto::write(*store, wconn, path); + WorkerProto::write(*store, wconn, info.deriver); + WorkerProto::write(*store, wconn, info.references); + conn.to << info.downloadSize << info.narSize; } break; } @@ -1055,7 +1054,7 @@ void processConnection(ref store, FdSource && from, FdSink && to, Trusted Finally finally([&]() { setInterrupted(false); - printMsgUsing(prevLogger, lvlDebug, "%d operations", opCount); + printMsgUsing(prevLogger, Verbosity::Debug, "%d operations", opCount); }); conn.postHandshake( @@ -1086,7 +1085,7 @@ void processConnection(ref store, FdSource && from, FdSink && to, Trusted break; } - printMsgUsing(prevLogger, lvlDebug, "received daemon op %d", op); + printMsgUsing(prevLogger, Verbosity::Debug, "received daemon op %d", op); opCount++; diff --git a/src/libstore/derivations.cc b/src/libstore/derivations.cc index 842ef9056ee..cb723d8b5dc 100644 --- a/src/libstore/derivations.cc +++ b/src/libstore/derivations.cc @@ -14,6 +14,7 @@ #include #include #include +#include namespace nix { @@ -109,8 +110,8 @@ bool BasicDerivation::isBuiltin() const static auto infoForDerivation(Store & store, const Derivation & drv) { auto references = drv.inputSrcs; - for (auto & i : drv.inputDrvs.map) - references.insert(i.first); + for (auto & [drvPath, _] : drv.inputDrvs.map) + references.insert(drvPath); /* Note that the outputs of a derivation are *not* references (that can be missing (of course) and should not necessarily be held during a garbage collection). */ @@ -625,11 +626,7 @@ static void unparseDerivedPathMapNode( */ static bool hasDynamicDrvDep(const Derivation & drv) { - return std::find_if( - drv.inputDrvs.map.begin(), - drv.inputDrvs.map.end(), - [](auto & kv) { return !kv.second.childMap.empty(); }) - != drv.inputDrvs.map.end(); + return std::ranges::any_of(drv.inputDrvs.map, [](auto & kv) { return !kv.second.childMap.empty(); }); } std::string Derivation::unparse( @@ -652,13 +649,13 @@ std::string Derivation::unparse( bool first = true; s += '['; - for (auto & i : outputs) { + for (auto & [outputName, output] : outputs) { if (first) first = false; else s += ','; s += '('; - printUnquotedString(s, i.first); + printUnquotedString(s, outputName); std::visit( overloaded{ [&](const DerivationOutput::InputAddressed & doi) { @@ -671,7 +668,8 @@ std::string Derivation::unparse( }, [&](const DerivationOutput::CAFixed & dof) { s += ','; - printUnquotedString(s, maskOutputs ? ""sv : store.printStorePath(dof.path(store, name, i.first))); + printUnquotedString( + s, maskOutputs ? ""sv : store.printStorePath(dof.path(store, name, outputName))); s += ','; printUnquotedString(s, dof.ca.printMethodAlgo()); s += ','; @@ -702,7 +700,7 @@ std::string Derivation::unparse( s += ','; printUnquotedString(s, "impure"sv); }}, - i.second.raw); + output.raw); s += ')'; } @@ -747,15 +745,15 @@ std::string Derivation::unparse( first = true; auto unparseEnv = [&](const StringPairs atermEnv) { - for (auto & i : atermEnv) { + for (auto & [envKey, envValue] : atermEnv) { if (first) first = false; else s += ','; s += '('; - printString(s, i.first); + printString(s, envKey); s += ','; - printString(s, maskOutputs && outputs.count(i.first) ? ""sv : i.second); + printString(s, maskOutputs && outputs.count(envKey) ? ""sv : envValue); s += ')'; } }; @@ -805,7 +803,7 @@ DerivationType BasicDerivation::type() const throw Error("only one fixed output is allowed for now"); }; - for (auto & i : outputs) { + for (auto & [outputName, output] : outputs) { std::visit( overloaded{ [&](const DerivationOutput::InputAddressed &) { @@ -820,7 +818,7 @@ DerivationType BasicDerivation::type() const .sandboxed = false, .fixed = true, }); - if (i.first != "out"sv) + if (outputName != "out"sv) throw Error("single fixed output must be named \"out\""); }, [&](const DerivationOutput::CAFloating & dof) { @@ -842,7 +840,7 @@ DerivationType BasicDerivation::type() const }, [&](const DerivationOutput::Impure &) { decide(DerivationType::Impure{}); }, }, - i.second.raw); + output.raw); } if (!ty) @@ -895,13 +893,13 @@ DrvHash hashDerivationModulo(Store & store, const Derivation & drv, bool maskOut /* Return a fixed hash for fixed-output derivations. */ if (type.isFixed()) { std::map outputHashes; - for (const auto & i : drv.outputs) { - auto & dof = std::get(i.second.raw); + for (const auto & [outputName, output] : drv.outputs) { + auto & dof = std::get(output.raw); auto hash = hashString( HashAlgorithm::SHA256, "fixed:out:" + dof.ca.printMethodAlgo() + ":" + dof.ca.hash.to_string(HashFormat::Base16, false) + ":" - + store.printStorePath(dof.path(store, drv.name, i.first))); - outputHashes.insert_or_assign(i.first, std::move(hash)); + + store.printStorePath(dof.path(store, drv.name, outputName))); + outputHashes.insert_or_assign(outputName, std::move(hash)); } return DrvHash{ .hashes = outputHashes, @@ -965,8 +963,8 @@ static DerivationOutput readDerivationOutput(Source & in, const StoreDirConfig & StringSet BasicDerivation::outputNames() const { StringSet names; - for (auto & i : outputs) - names.insert(i.first); + for (auto & [outputName, _] : outputs) + names.insert(outputName); return names; } @@ -1017,8 +1015,8 @@ Source & readDerivation(Source & in, const StoreDirConfig & store, BasicDerivati void writeDerivation(Sink & out, const StoreDirConfig & store, const BasicDerivation & drv) { out << drv.outputs.size(); - for (auto & i : drv.outputs) { - out << i.first; + for (auto & [outputName, output] : drv.outputs) { + out << outputName; std::visit( overloaded{ [&](const DerivationOutput::InputAddressed & doi) { @@ -1026,7 +1024,7 @@ void writeDerivation(Sink & out, const StoreDirConfig & store, const BasicDeriva << ""; }, [&](const DerivationOutput::CAFixed & dof) { - out << store.printStorePath(dof.path(store, drv.name, i.first)) << dof.ca.printMethodAlgo() + out << store.printStorePath(dof.path(store, drv.name, outputName)) << dof.ca.printMethodAlgo() << dof.ca.hash.to_string(HashFormat::Base16, false); }, [&](const DerivationOutput::CAFloating & dof) { @@ -1041,7 +1039,7 @@ void writeDerivation(Sink & out, const StoreDirConfig & store, const BasicDeriva out << "" << (std::string{doi.method.renderPrefix()} + printHashAlgo(doi.hashAlgo)) << "impure"; }, }, - i.second.raw); + output.raw); } CommonProto::write(store, CommonProto::WriteConn{.to = out}, drv.inputSrcs); out << drv.platform << drv.builder << drv.args; @@ -1077,18 +1075,18 @@ void BasicDerivation::applyRewrites(const StringMap & rewrites) debug("rewriting the derivation"); - for (auto & rewrite : rewrites) - debug("rewriting %s as %s", rewrite.first, rewrite.second); + for (auto & [from, to] : rewrites) + debug("rewriting %s as %s", from, to); builder = rewriteStrings(builder, rewrites); for (auto & arg : args) arg = rewriteStrings(arg, rewrites); StringPairs newEnv; - for (auto & envVar : env) { - auto envName = rewriteStrings(envVar.first, rewrites); - auto envValue = rewriteStrings(envVar.second, rewrites); - newEnv.emplace(envName, envValue); + for (auto & [envName, envValue] : env) { + auto newName = rewriteStrings(envName, rewrites); + auto newValue = rewriteStrings(envValue, rewrites); + newEnv.emplace(newName, newValue); } env = std::move(newEnv); diff --git a/src/libstore/export-import.cc b/src/libstore/export-import.cc index a343b5837db..075dd938225 100644 --- a/src/libstore/export-import.cc +++ b/src/libstore/export-import.cc @@ -6,6 +6,7 @@ #include "nix/store/common-protocol-impl.hh" #include +#include namespace nix { @@ -37,7 +38,7 @@ static void exportPath(Store & store, const StorePath & path, Sink & sink) void exportPaths(Store & store, const StorePathSet & paths, Sink & sink) { auto sorted = store.topoSortPaths(paths); - std::reverse(sorted.begin(), sorted.end()); + std::ranges::reverse(sorted); for (auto & path : sorted) { sink << 1; @@ -69,7 +70,7 @@ StorePaths importPaths(Store & store, Source & source, CheckSigsFlag checkSigs) auto path = store.parseStorePath(readString(source)); - // Activity act(*logger, lvlInfo, "importing path '%s'", info.path); + // Activity act(*logger, Verbosity::Info, "importing path '%s'", info.path); auto references = CommonProto::Serialise::read(store, CommonProto::ReadConn{.from = source}); auto deriver = readString(source); diff --git a/src/libstore/filetransfer.cc b/src/libstore/filetransfer.cc index 57caec38430..959507956df 100644 --- a/src/libstore/filetransfer.cc +++ b/src/libstore/filetransfer.cc @@ -99,8 +99,8 @@ struct curlFileTransfer : public FileTransfer : fileTransfer(fileTransfer) , request(request) , act(*logger, - lvlTalkative, - actFileTransfer, + Verbosity::Talkative, + ActivityType::FileTransfer, fmt("%sing '%s'", request.verb(), request.uri), {request.uri.to_string()}, request.parentAct) @@ -136,8 +136,8 @@ struct curlFileTransfer : public FileTransfer requestHeaders = curl_slist_append(requestHeaders, ("If-None-Match: " + request.expectedETag).c_str()); if (!request.mimeType.empty()) requestHeaders = curl_slist_append(requestHeaders, ("Content-Type: " + request.mimeType).c_str()); - for (auto it = request.headers.begin(); it != request.headers.end(); ++it) { - requestHeaders = curl_slist_append(requestHeaders, fmt("%s: %s", it->first, it->second).c_str()); + for (auto & [key, value] : request.headers) { + requestHeaders = curl_slist_append(requestHeaders, fmt("%s: %s", key, value).c_str()); } } @@ -234,7 +234,7 @@ struct curlFileTransfer : public FileTransfer try { size_t realSize = size * nmemb; std::string line((char *) contents, realSize); - printMsg(lvlVomit, "got header for '%s': %s", request.uri, trim(line)); + printMsg(Verbosity::Vomit, "got header for '%s': %s", request.uri, trim(line)); static std::regex statusLine("HTTP/[^ ]+ +[0-9]+(.*)", std::regex::extended | std::regex::icase); if (std::smatch match; std::regex_match(line, match, statusLine)) { @@ -395,7 +395,7 @@ struct curlFileTransfer : public FileTransfer curl_easy_reset(req); - if (verbosity >= lvlVomit) { + if (verbosity >= Verbosity::Vomit) { curl_easy_setopt(req, CURLOPT_VERBOSE, 1); curl_easy_setopt(req, CURLOPT_DEBUGFUNCTION, TransferItem::debugCallback); } diff --git a/src/libstore/gc.cc b/src/libstore/gc.cc index 4846d445fe1..4fabbc15b8a 100644 --- a/src/libstore/gc.cc +++ b/src/libstore/gc.cc @@ -887,7 +887,7 @@ void LocalStore::collectGarbage(const GCOptions & options, GCResults & results) continue; } - printMsg(lvlTalkative, "deleting unused link '%1%'", path); + printMsg(Verbosity::Talkative, "deleting unused link '%1%'", path); if (unlink(path.c_str()) == -1) throw SysError("deleting '%1%'", path); diff --git a/src/libstore/globals.cc b/src/libstore/globals.cc index 8c542b686c2..9d3f97ca892 100644 --- a/src/libstore/globals.cc +++ b/src/libstore/globals.cc @@ -218,8 +218,8 @@ StringSet Settings::getDefaultExtraPlatforms() #ifdef __linux__ StringSet levels = computeLevels(); - for (auto iter = levels.begin(); iter != levels.end(); ++iter) - extraPlatforms.insert(*iter + "-linux"); + for (auto & level : levels) + extraPlatforms.insert(level + "-linux"); #elif defined(__APPLE__) // Rosetta 2 emulation layer can run x86_64 binaries on aarch64 // machines. Note that we can’t force processes from executing @@ -272,20 +272,20 @@ std::string nixVersion = PACKAGE_VERSION; NLOHMANN_JSON_SERIALIZE_ENUM( SandboxMode, { - {SandboxMode::smEnabled, true}, - {SandboxMode::smRelaxed, "relaxed"}, - {SandboxMode::smDisabled, false}, + {SandboxMode::Enabled, true}, + {SandboxMode::Relaxed, "relaxed"}, + {SandboxMode::Disabled, false}, }); template<> SandboxMode BaseSetting::parse(const std::string & str) const { if (str == "true") - return smEnabled; + return SandboxMode::Enabled; else if (str == "relaxed") - return smRelaxed; + return SandboxMode::Relaxed; else if (str == "false") - return smDisabled; + return SandboxMode::Disabled; else throw UsageError("option '%s' has invalid value '%s'", name, str); } @@ -299,11 +299,11 @@ struct BaseSetting::trait template<> std::string BaseSetting::to_string() const { - if (value == smEnabled) + if (value == SandboxMode::Enabled) return "true"; - else if (value == smRelaxed) + else if (value == SandboxMode::Relaxed) return "relaxed"; - else if (value == smDisabled) + else if (value == SandboxMode::Disabled) return "false"; else unreachable(); @@ -317,21 +317,21 @@ void BaseSetting::convertToArg(Args & args, const std::string & cat .aliases = aliases, .description = "Enable sandboxing.", .category = category, - .handler = {[this]() { override(smEnabled); }}, + .handler = {[this]() { override(SandboxMode::Enabled); }}, }); args.addFlag({ .longName = "no-" + name, .aliases = aliases, .description = "Disable sandboxing.", .category = category, - .handler = {[this]() { override(smDisabled); }}, + .handler = {[this]() { override(SandboxMode::Disabled); }}, }); args.addFlag({ .longName = "relaxed-" + name, .aliases = aliases, .description = "Enable sandboxing, but allow builds to disable it.", .category = category, - .handler = {[this]() { override(smRelaxed); }}, + .handler = {[this]() { override(SandboxMode::Relaxed); }}, }); } diff --git a/src/libstore/include/nix/store/build/derivation-building-goal.hh b/src/libstore/include/nix/store/build/derivation-building-goal.hh index be95c796b05..c5f085bbb5c 100644 --- a/src/libstore/include/nix/store/build/derivation-building-goal.hh +++ b/src/libstore/include/nix/store/build/derivation-building-goal.hh @@ -20,7 +20,7 @@ struct HookInstance; struct DerivationBuilder; #endif -typedef enum { rpAccept, rpDecline, rpPostpone } HookReply; +enum class HookReply { Accept, Decline, Postpone }; /** * A goal for building a derivation. Substitution, (or any other method of diff --git a/src/libstore/include/nix/store/build/worker.hh b/src/libstore/include/nix/store/build/worker.hh index 173f7b222b7..03be8b9fd36 100644 --- a/src/libstore/include/nix/store/build/worker.hh +++ b/src/libstore/include/nix/store/build/worker.hh @@ -355,8 +355,8 @@ public: actDerivations.progress(doneBuilds, expectedBuilds + doneBuilds, runningBuilds, failedBuilds); actSubstitutions.progress( doneSubstitutions, expectedSubstitutions + doneSubstitutions, runningSubstitutions, failedSubstitutions); - act.setExpected(actFileTransfer, expectedDownloadSize + doneDownloadSize); - act.setExpected(actCopyPath, expectedNarSize + doneNarSize); + act.setExpected(ActivityType::FileTransfer, expectedDownloadSize + doneDownloadSize); + act.setExpected(ActivityType::CopyPath, expectedNarSize + doneNarSize); } }; diff --git a/src/libstore/include/nix/store/export-import.hh b/src/libstore/include/nix/store/export-import.hh index 15092202f1f..63e0ca4e56d 100644 --- a/src/libstore/include/nix/store/export-import.hh +++ b/src/libstore/include/nix/store/export-import.hh @@ -7,7 +7,7 @@ namespace nix { /** * Magic header of exportPath() output (obsolete). */ -const uint32_t exportMagic = 0x4558494e; +constexpr uint32_t exportMagic = 0x4558494e; /** * Export multiple paths in the format expected by `nix-store diff --git a/src/libstore/include/nix/store/globals.hh b/src/libstore/include/nix/store/globals.hh index 5ddfbee302b..518f224413c 100644 --- a/src/libstore/include/nix/store/globals.hh +++ b/src/libstore/include/nix/store/globals.hh @@ -17,7 +17,7 @@ namespace nix { -typedef enum { smEnabled, smRelaxed, smDisabled } SandboxMode; +enum class SandboxMode { Enabled, Relaxed, Disabled }; template<> SandboxMode BaseSetting::parse(const std::string & str) const; @@ -54,7 +54,7 @@ struct MaxBuildJobsSetting : public BaseSetting unsigned int parse(const std::string & str) const override; }; -const uint32_t maxIdsPerBuild = +constexpr uint32_t maxIdsPerBuild = #ifdef __linux__ 1 << 16 #else @@ -679,9 +679,9 @@ public: Setting sandboxMode{ this, #ifdef __linux__ - smEnabled + SandboxMode::Enabled #else - smDisabled + SandboxMode::Disabled #endif , "sandbox", diff --git a/src/libstore/include/nix/store/local-store.hh b/src/libstore/include/nix/store/local-store.hh index 212229e42f9..536b8e1c5c8 100644 --- a/src/libstore/include/nix/store/local-store.hh +++ b/src/libstore/include/nix/store/local-store.hh @@ -23,7 +23,7 @@ namespace nix { * Version 4 is Nix 0.11. Version 5 is Nix 0.12-0.16. Version 6 is * Nix 1.0. Version 7 is Nix 1.3. Version 10 is 2.0. */ -const int nixSchemaVersion = 10; +constexpr int nixSchemaVersion = 10; struct OptimiseStats { diff --git a/src/libstore/include/nix/store/path-info.hh b/src/libstore/include/nix/store/path-info.hh index a64e8458d33..06b234a0d9d 100644 --- a/src/libstore/include/nix/store/path-info.hh +++ b/src/libstore/include/nix/store/path-info.hh @@ -153,7 +153,7 @@ struct ValidPathInfo : virtual UnkeyedValidPathInfo */ bool isContentAddressed(const StoreDirConfig & store) const; - static const size_t maxSigs = std::numeric_limits::max(); + static constexpr size_t maxSigs = std::numeric_limits::max(); /** * Return the number of signatures on this .narinfo that were diff --git a/src/libstore/include/nix/store/sqlite.hh b/src/libstore/include/nix/store/sqlite.hh index 3495c0bd143..b3ba4eedc37 100644 --- a/src/libstore/include/nix/store/sqlite.hh +++ b/src/libstore/include/nix/store/sqlite.hh @@ -68,7 +68,7 @@ struct SQLite void exec(const std::string & stmt); - uint64_t getLastInsertedRowId(); + uint64_t getLastInsertedRowId() const; }; /** @@ -131,9 +131,9 @@ struct SQLiteStmt */ bool next(); - std::string getStr(int col); - int64_t getInt(int col); - bool isNull(int col); + std::string getStr(int col) const; + int64_t getInt(int col) const; + bool isNull(int col) const; }; Use use() diff --git a/src/libstore/include/nix/store/store-api.hh b/src/libstore/include/nix/store/store-api.hh index 9535227eb17..926441801fc 100644 --- a/src/libstore/include/nix/store/store-api.hh +++ b/src/libstore/include/nix/store/store-api.hh @@ -294,13 +294,13 @@ protected: * Whether the value is valid as a cache entry. The path may not * exist. */ - bool isKnownNow(); + bool isKnownNow() const; /** * Past tense, because a path can only be assumed to exists when * isKnownNow() && didExist() */ - inline bool didExist() + inline bool didExist() const { return value != nullptr; } @@ -373,7 +373,7 @@ public: unsupported("queryAllValidPaths"); } - constexpr static const char * MissingName = "x"; + static constexpr const char * MissingName = "x"; /** * Query information about a valid path. It is permitted to omit diff --git a/src/libstore/local-overlay-store.cc b/src/libstore/local-overlay-store.cc index c8aa1d1a2b6..d6768eff59f 100644 --- a/src/libstore/local-overlay-store.cc +++ b/src/libstore/local-overlay-store.cc @@ -233,7 +233,7 @@ void LocalOverlayStore::deleteStorePath(const Path & path, uint64_t & bytesFreed void LocalOverlayStore::optimiseStore() { - Activity act(*logger, actOptimiseStore); + Activity act(*logger, ActivityType::OptimiseStore); // Note for LocalOverlayStore, queryAllValidPaths only returns paths in upper layer auto paths = queryAllValidPaths(); diff --git a/src/libstore/local-store.cc b/src/libstore/local-store.cc index a849576f6ee..3c2cdc27166 100644 --- a/src/libstore/local-store.cc +++ b/src/libstore/local-store.cc @@ -76,9 +76,7 @@ std::string LocalStoreConfig::doc() Path LocalBuildStoreConfig::getBuildDir() const { - return settings.buildDir.get().has_value() ? *settings.buildDir.get() - : buildDir.get().has_value() ? *buildDir.get() - : stateDir.get() + "/builds"; + return settings.buildDir.get().or_else([&]() { return buildDir.get(); }).value_or(stateDir.get() + "/builds"); } ref LocalStore::Config::openStore() const @@ -714,11 +712,12 @@ uint64_t LocalStore::addValidPath(State & state, const ValidPathInfo & info, boo if (checkOutputs) drv.checkInvariants(*this, info.path); - for (auto & i : drv.outputsAndOptPaths(*this)) { + for (auto & [outputName, outputAndPath] : drv.outputsAndOptPaths(*this)) { + auto & [_, optPath] = outputAndPath; /* Floating CA derivations have indeterminate output paths until they are built, so don't register anything in that case */ - if (i.second.second) - cacheDrvOutputMapping(state, id, i.first, *i.second.second); + if (optPath) + cacheDrvOutputMapping(state, id, outputName, *optPath); } } @@ -1382,7 +1381,7 @@ bool LocalStore::verifyStore(bool checkContents, RepairFlag repair) for (auto & link : DirectoryIterator{linksDir}) { checkInterrupt(); auto name = link.path().filename(); - printMsg(lvlTalkative, "checking contents of %s", name); + printMsg(Verbosity::Talkative, "checking contents of %s", name); std::string hash = hashPath(makeFSSourceAccessor(link.path()), FileIngestionMethod::NixArchive, HashAlgorithm::SHA256) .first.to_string(HashFormat::Nix32, false); @@ -1407,7 +1406,7 @@ bool LocalStore::verifyStore(bool checkContents, RepairFlag repair) std::const_pointer_cast(std::shared_ptr(queryPathInfo(i))); /* Check the content hash (optionally - slow). */ - printMsg(lvlTalkative, "checking contents of '%s'", printStorePath(i)); + printMsg(Verbosity::Talkative, "checking contents of '%s'", printStorePath(i)); auto hashSink = HashSink(info->narHash.algo); diff --git a/src/libstore/machines.cc b/src/libstore/machines.cc index d614676668b..672ad08404d 100644 --- a/src/libstore/machines.cc +++ b/src/libstore/machines.cc @@ -4,6 +4,7 @@ #include "nix/store/store-open.hh" #include +#include namespace nix { @@ -45,16 +46,14 @@ bool Machine::systemSupported(const std::string & system) const bool Machine::allSupported(const StringSet & features) const { - return std::all_of(features.begin(), features.end(), [&](const std::string & feature) { + return std::ranges::all_of(features, [&](const std::string & feature) { return supportedFeatures.count(feature) || mandatoryFeatures.count(feature); }); } bool Machine::mandatoryMet(const StringSet & features) const { - return std::all_of(mandatoryFeatures.begin(), mandatoryFeatures.end(), [&](const std::string & feature) { - return features.count(feature); - }); + return std::ranges::all_of(mandatoryFeatures, [&](const std::string & feature) { return features.count(feature); }); } StoreReference Machine::completeStoreReference() const diff --git a/src/libstore/make-content-addressed.cc b/src/libstore/make-content-addressed.cc index 4a7b21c3b12..d3328bda9af 100644 --- a/src/libstore/make-content-addressed.cc +++ b/src/libstore/make-content-addressed.cc @@ -1,6 +1,8 @@ #include "nix/store/make-content-addressed.hh" #include "nix/store/references.hh" +#include + namespace nix { std::map makeContentAddressed(Store & srcStore, Store & dstStore, const StorePathSet & storePaths) @@ -10,7 +12,7 @@ std::map makeContentAddressed(Store & srcStore, Store & ds auto paths = srcStore.topoSortPaths(closure); - std::reverse(paths.begin(), paths.end()); + std::ranges::reverse(paths); std::map remappings; diff --git a/src/libstore/misc.cc b/src/libstore/misc.cc index 9d11648d2a6..d990301d8a3 100644 --- a/src/libstore/misc.cc +++ b/src/libstore/misc.cc @@ -100,7 +100,7 @@ const ContentAddress * getDerivationCA(const BasicDerivation & drv) MissingPaths Store::queryMissing(const std::vector & targets) { - Activity act(*logger, lvlDebug, actUnknown, "querying info about missing paths"); + Activity act(*logger, Verbosity::Debug, ActivityType::Unknown, "querying info about missing paths"); // FIXME: make async. ThreadPool pool(fileTransferSettings.httpConnections); diff --git a/src/libstore/optimise-store.cc b/src/libstore/optimise-store.cc index dca093e04c7..e964b88ed37 100644 --- a/src/libstore/optimise-store.cc +++ b/src/libstore/optimise-store.cc @@ -63,7 +63,7 @@ LocalStore::InodeHash LocalStore::loadInodeHash() if (errno) throw SysError("reading directory '%1%'", linksDir); - printMsg(lvlTalkative, "loaded %1% hash inodes", inodeHash.size()); + printMsg(Verbosity::Talkative, "loaded %1% hash inodes", inodeHash.size()); return inodeHash; } @@ -220,7 +220,7 @@ void LocalStore::optimisePath_( return; } - printMsg(lvlTalkative, "linking '%1%' to %2%", path, linkPath); + printMsg(Verbosity::Talkative, "linking '%1%' to %2%", path, linkPath); /* Make the containing directory writable, but only if it's not the store itself (we don't want or need to mess with its @@ -273,7 +273,7 @@ void LocalStore::optimisePath_( if (act) act->result( - resFileLinked, + ResultType::FileLinked, st.st_size #ifndef _WIN32 , @@ -284,7 +284,7 @@ void LocalStore::optimisePath_( void LocalStore::optimiseStore(OptimiseStats & stats) { - Activity act(*logger, actOptimiseStore); + Activity act(*logger, ActivityType::OptimiseStore); auto paths = queryAllValidPaths(); InodeHash inodeHash = loadInodeHash(); @@ -298,7 +298,8 @@ void LocalStore::optimiseStore(OptimiseStats & stats) if (!isValidPath(i)) continue; /* path was GC'ed, probably */ { - Activity act(*logger, lvlTalkative, actUnknown, fmt("optimising path '%s'", printStorePath(i))); + Activity act( + *logger, Verbosity::Talkative, ActivityType::Unknown, fmt("optimising path '%s'", printStorePath(i))); optimisePath_(&act, stats, config->realStoreDir + "/" + std::string(i.to_string()), inodeHash, NoRepair); } done++; diff --git a/src/libstore/parsed-derivations.cc b/src/libstore/parsed-derivations.cc index 95434bd20ac..81a91407c6a 100644 --- a/src/libstore/parsed-derivations.cc +++ b/src/libstore/parsed-derivations.cc @@ -109,8 +109,8 @@ nlohmann::json::object_t StructuredAttrs::prepareStructuredAttrs( /* Add an "outputs" object containing the output paths. */ nlohmann::json outputsJson; - for (auto & i : outputs) - outputsJson[i.first] = hashPlaceholder(i.first); + for (auto & [outputName, _] : outputs) + outputsJson[outputName] = hashPlaceholder(outputName); json["outputs"] = std::move(outputsJson); /* Handle exportReferencesGraph. */ diff --git a/src/libstore/posix-fs-canonicalise.cc b/src/libstore/posix-fs-canonicalise.cc index a274468c329..cb46cf12123 100644 --- a/src/libstore/posix-fs-canonicalise.cc +++ b/src/libstore/posix-fs-canonicalise.cc @@ -13,7 +13,7 @@ namespace nix { -const time_t mtimeStore = 1; /* 1 second into the epoch */ +constexpr time_t mtimeStore = 1; /* 1 second into the epoch */ static void canonicaliseTimestampAndPermissions(const Path & path, const struct stat & st) { diff --git a/src/libstore/remote-fs-accessor.cc b/src/libstore/remote-fs-accessor.cc index 51bab995354..af73412e7f1 100644 --- a/src/libstore/remote-fs-accessor.cc +++ b/src/libstore/remote-fs-accessor.cc @@ -94,26 +94,26 @@ std::shared_ptr RemoteFSAccessor::accessObject(const StorePath & std::optional RemoteFSAccessor::maybeLstat(const CanonPath & path) { - auto res = fetch(path); - return res.first->maybeLstat(res.second); + auto [accessor, subPath] = fetch(path); + return accessor->maybeLstat(subPath); } SourceAccessor::DirEntries RemoteFSAccessor::readDirectory(const CanonPath & path) { - auto res = fetch(path); - return res.first->readDirectory(res.second); + auto [accessor, subPath] = fetch(path); + return accessor->readDirectory(subPath); } std::string RemoteFSAccessor::readFile(const CanonPath & path) { - auto res = fetch(path); - return res.first->readFile(res.second); + auto [accessor, subPath] = fetch(path); + return accessor->readFile(subPath); } std::string RemoteFSAccessor::readLink(const CanonPath & path) { - auto res = fetch(path); - return res.first->readLink(res.second); + auto [accessor, subPath] = fetch(path); + return accessor->readLink(subPath); } } // namespace nix diff --git a/src/libstore/remote-store.cc b/src/libstore/remote-store.cc index b07efc0241a..d90517d0134 100644 --- a/src/libstore/remote-store.cc +++ b/src/libstore/remote-store.cc @@ -106,9 +106,10 @@ void RemoteStore::initConnection(Connection & conn) void RemoteStore::setOptions(Connection & conn) { conn.to << WorkerProto::Op::SetOptions << settings.keepFailed << settings.keepGoing << settings.tryFallback - << verbosity << settings.maxBuildJobs << settings.maxSilentTime << true - << (settings.verboseBuild ? lvlError : lvlVomit) << 0 // obsolete log type - << 0 /* obsolete print build trace */ + << static_cast(verbosity) << settings.maxBuildJobs << settings.maxSilentTime << true + << static_cast(settings.verboseBuild ? Verbosity::Error : Verbosity::Vomit) + << 0 // obsolete log type + << 0 /* obsolete print build trace */ << settings.buildCores << settings.useSubstitutes; std::map overrides; @@ -452,7 +453,7 @@ void RemoteStore::addMultipleToStore( for (auto & [pathInfo, _] : pathsToCopy) { bytesExpected += pathInfo.narSize; } - act.setExpected(actCopyPath, bytesExpected); + act.setExpected(ActivityType::CopyPath, bytesExpected); auto source = sinkToSource([&](Sink & sink) { size_t nrTotal = pathsToCopy.size(); diff --git a/src/libstore/sqlite.cc b/src/libstore/sqlite.cc index 5f0b3ce51a1..a094253f41e 100644 --- a/src/libstore/sqlite.cc +++ b/src/libstore/sqlite.cc @@ -136,7 +136,7 @@ void SQLite::exec(const std::string & stmt) }); } -uint64_t SQLite::getLastInsertedRowId() +uint64_t SQLite::getLastInsertedRowId() const { return sqlite3_last_insert_rowid(db); } @@ -233,20 +233,20 @@ bool SQLiteStmt::Use::next() return r == SQLITE_ROW; } -std::string SQLiteStmt::Use::getStr(int col) +std::string SQLiteStmt::Use::getStr(int col) const { auto s = (const char *) sqlite3_column_text(stmt, col); assert(s); return s; } -int64_t SQLiteStmt::Use::getInt(int col) +int64_t SQLiteStmt::Use::getInt(int col) const { // FIXME: detect nulls? return sqlite3_column_int64(stmt, col); } -bool SQLiteStmt::Use::isNull(int col) +bool SQLiteStmt::Use::isNull(int col) const { return sqlite3_column_type(stmt, col) == SQLITE_NULL; } diff --git a/src/libstore/ssh.cc b/src/libstore/ssh.cc index 1a99083669c..8e53d427787 100644 --- a/src/libstore/ssh.cc +++ b/src/libstore/ssh.cc @@ -186,7 +186,7 @@ std::unique_ptr SSHMaster::startCommand(Strings && comman addCommonSSHOpts(args); if (socketPath != "") args.insert(args.end(), {"-S", socketPath}); - if (verbosity >= lvlChatty) + if (verbosity >= Verbosity::Chatty) args.push_back("-v"); args.splice(args.end(), std::move(extraSshArgs)); args.push_back("--"); @@ -261,7 +261,7 @@ Path SSHMaster::startMaster() throw SysError("duping over stdout"); Strings args = {"ssh", hostnameAndUser.c_str(), "-M", "-N", "-S", state->socketPath}; - if (verbosity >= lvlChatty) + if (verbosity >= Verbosity::Chatty) args.push_back("-v"); addCommonSSHOpts(args); auto env = createSSHEnv(); diff --git a/src/libstore/store-api.cc b/src/libstore/store-api.cc index 52130668ce5..ca3d836a391 100644 --- a/src/libstore/store-api.cc +++ b/src/libstore/store-api.cc @@ -20,6 +20,7 @@ #include "nix/util/signals.hh" #include +#include #include #include "nix/util/strings.hh" @@ -131,12 +132,13 @@ void Store::addMultipleToStore(PathsSource && pathsToCopy, Activity & act, Repai std::map infosMap; StorePathSet storePathsToAdd; for (auto & thingToAdd : pathsToCopy) { - bytesExpected += thingToAdd.first.narSize; - infosMap.insert_or_assign(thingToAdd.first.path, &thingToAdd); - storePathsToAdd.insert(thingToAdd.first.path); + auto & [info, _] = thingToAdd; + bytesExpected += info.narSize; + infosMap.insert_or_assign(info.path, &thingToAdd); + storePathsToAdd.insert(info.path); } - act.setExpected(actCopyPath, bytesExpected); + act.setExpected(ActivityType::CopyPath, bytesExpected); auto showProgress = [&, nrTotal = pathsToCopy.size()]() { act.progress(nrDone, nrTotal, nrRunning, nrFailed); }; @@ -178,7 +180,7 @@ void Store::addMultipleToStore(PathsSource && pathsToCopy, Activity & act, Repai nrFailed++; if (!settings.keepGoing) throw e; - printMsg(lvlError, "could not copy %s: %s", printStorePath(path), e.what()); + printMsg(Verbosity::Error, "could not copy %s: %s", printStorePath(path), e.what()); showProgress(); return; } @@ -333,7 +335,7 @@ StoreReference StoreConfig::getReference() const return {.variant = StoreReference::Auto{}}; } -bool Store::PathInfoCacheValue::isKnownNow() +bool Store::PathInfoCacheValue::isKnownNow() const { std::chrono::duration ttl = didExist() ? std::chrono::seconds(settings.ttlPositiveNarInfoCache) : std::chrono::seconds(settings.ttlNegativeNarInfoCache); @@ -399,8 +401,8 @@ StorePathSet Store::queryDerivationOutputs(const StorePath & path) { auto outputMap = this->queryDerivationOutputMap(path); StorePathSet outputPaths; - for (auto & i : outputMap) { - outputPaths.emplace(std::move(i.second)); + for (auto & [_, output] : outputMap) { + outputPaths.emplace(std::move(output)); } return outputPaths; } @@ -861,8 +863,8 @@ void copyStorePath( auto storePathS = srcStore.printStorePath(storePath); Activity act( *logger, - lvlInfo, - actCopyPath, + Verbosity::Info, + ActivityType::CopyPath, makeCopyPathMessage(srcCfg, dstCfg, storePathS), {storePathS, srcCfg.getHumanReadableURI(), dstCfg.getHumanReadableURI()}); PushActivity pact(act.id); @@ -973,12 +975,12 @@ std::map copyPaths( if (!valid.count(path)) missing.insert(path); - Activity act(*logger, lvlInfo, actCopyPaths, fmt("copying %d paths", missing.size())); + Activity act(*logger, Verbosity::Info, ActivityType::CopyPaths, fmt("copying %d paths", missing.size())); // In the general case, `addMultipleToStore` requires a sorted list of // store paths to add, so sort them right now auto sortedMissing = srcStore.topoSortPaths(missing); - std::reverse(sortedMissing.begin(), sortedMissing.end()); + std::ranges::reverse(sortedMissing); std::map pathsMap; for (auto & path : storePaths) @@ -1022,8 +1024,8 @@ std::map copyPaths( auto storePathS = srcStore.printStorePath(missingPath); Activity act( *logger, - lvlInfo, - actCopyPath, + Verbosity::Info, + ActivityType::CopyPath, makeCopyPathMessage(srcCfg, dstCfg, storePathS), {storePathS, srcCfg.getHumanReadableURI(), dstCfg.getHumanReadableURI()}); PushActivity pact(act.id); diff --git a/src/libstore/store-reference.cc b/src/libstore/store-reference.cc index 01e197be76d..6cf19694c1b 100644 --- a/src/libstore/store-reference.cc +++ b/src/libstore/store-reference.cc @@ -9,14 +9,14 @@ namespace nix { -static bool isNonUriPath(const std::string & spec) +static bool isNonUriPath(std::string_view spec) { return // is not a URL - spec.find("://") == std::string::npos + spec.find("://") == std::string_view::npos // Has at least one path separator, and so isn't a single word that // might be special like "auto" - && spec.find("/") != std::string::npos; + && spec.find("/") != std::string_view::npos; } std::string StoreReference::render(bool withParams) const diff --git a/src/libstore/unix/build/chroot-derivation-builder.cc b/src/libstore/unix/build/chroot-derivation-builder.cc index 2e52999726b..69b754647ef 100644 --- a/src/libstore/unix/build/chroot-derivation-builder.cc +++ b/src/libstore/unix/build/chroot-derivation-builder.cc @@ -64,7 +64,7 @@ struct ChrootDerivationBuilder : virtual DerivationBuilderImpl /* Clean up the chroot directory automatically. */ autoDelChroot = std::make_shared(chrootParentDir); - printMsg(lvlChatty, "setting up chroot environment in '%1%'", chrootParentDir); + printMsg(Verbosity::Chatty, "setting up chroot environment in '%1%'", chrootParentDir); if (mkdir(chrootParentDir.c_str(), 0700) == -1) throw SysError("cannot create '%s'", chrootRootDir); diff --git a/src/libstore/unix/build/derivation-builder.cc b/src/libstore/unix/build/derivation-builder.cc index 333c4dff8fe..9200a1e412b 100644 --- a/src/libstore/unix/build/derivation-builder.cc +++ b/src/libstore/unix/build/derivation-builder.cc @@ -798,10 +798,10 @@ std::optional DerivationBuilderImpl::startBuild() startDaemon(); /* Run the builder. */ - printMsg(lvlChatty, "executing builder '%1%'", drv.builder); - printMsg(lvlChatty, "using builder args '%1%'", concatStringsSep(" ", drv.args)); + printMsg(Verbosity::Chatty, "executing builder '%1%'", drv.builder); + printMsg(Verbosity::Chatty, "using builder args '%1%'", concatStringsSep(" ", drv.args)); for (auto & i : drv.env) - printMsg(lvlVomit, "setting builder env variable '%1%'='%2%'", i.first, i.second); + printMsg(Verbosity::Vomit, "setting builder env variable '%1%'='%2%'", i.first, i.second); /* Create the log file. */ miscMethods->openLogFile(); @@ -884,7 +884,7 @@ PathsInChroot DerivationBuilderImpl::getPathsInSandbox() } if (settings.preBuildHook != "") { - printMsg(lvlChatty, "executing pre-build hook '%1%'", settings.preBuildHook); + printMsg(Verbosity::Chatty, "executing pre-build hook '%1%'", settings.preBuildHook); enum BuildHookState { stBegin, stExtraChrootDirs }; @@ -1956,7 +1956,7 @@ std::unique_ptr makeDerivationBuilder( /* Are we doing a sandboxed build? */ { - if (settings.sandboxMode == smEnabled) { + if (settings.sandboxMode == SandboxMode::Enabled) { if (params.drvOptions.noChroot) throw Error( "derivation '%s' has '__noChroot' set, " @@ -1970,9 +1970,9 @@ std::unique_ptr makeDerivationBuilder( store.printStorePath(params.drvPath)); #endif useSandbox = true; - } else if (settings.sandboxMode == smDisabled) + } else if (settings.sandboxMode == SandboxMode::Disabled) useSandbox = false; - else if (settings.sandboxMode == smRelaxed) + else if (settings.sandboxMode == SandboxMode::Relaxed) // FIXME: cache derivationType useSandbox = params.drv.type().isSandboxed() && !params.drvOptions.noChroot; } diff --git a/src/libstore/unix/build/hook-instance.cc b/src/libstore/unix/build/hook-instance.cc index 83824b51f75..aa03bfc2249 100644 --- a/src/libstore/unix/build/hook-instance.cc +++ b/src/libstore/unix/build/hook-instance.cc @@ -33,7 +33,7 @@ HookInstance::HookInstance() for (auto & arg : buildHookArgs) args.push_back(arg); - args.push_back(std::to_string(verbosity)); + args.push_back(std::to_string(static_cast(verbosity))); /* Create a pipe to get the output of the child. */ fromHook.create(); diff --git a/src/libstore/worker-protocol-connection.cc b/src/libstore/worker-protocol-connection.cc index 8a37662904d..bf3b52fc736 100644 --- a/src/libstore/worker-protocol-connection.cc +++ b/src/libstore/worker-protocol-connection.cc @@ -22,9 +22,9 @@ static Logger::Fields readFields(Source & from) size_t size = readInt(from); for (size_t n = 0; n < size; n++) { auto type = (decltype(Logger::Field::type)) readInt(from); - if (type == Logger::Field::tInt) + if (type == Logger::Field::Type::Int) fields.push_back(readNum(from)); - else if (type == Logger::Field::tString) + else if (type == Logger::Field::Type::String) fields.push_back(readString(from)); else throw Error("got unsupported field type %x from Nix daemon", (int) type); diff --git a/src/libutil-tests/logging.cc b/src/libutil-tests/logging.cc index e4ebccd490e..3537e117fbe 100644 --- a/src/libutil-tests/logging.cc +++ b/src/libutil-tests/logging.cc @@ -93,7 +93,7 @@ namespace nix { TEST(logEI, loggingErrorOnInfoLevel) { testing::internal::CaptureStderr(); - logger->logEI({ .level = lvlInfo, + logger->logEI({ .level = Verbosity::Info, .name = "Info name", }); @@ -102,11 +102,11 @@ namespace nix { } TEST(logEI, loggingErrorOnTalkativeLevel) { - verbosity = lvlTalkative; + verbosity = Verbosity::Talkative; testing::internal::CaptureStderr(); - logger->logEI({ .level = lvlTalkative, + logger->logEI({ .level = Verbosity::Talkative, .name = "Talkative name", }); @@ -115,11 +115,11 @@ namespace nix { } TEST(logEI, loggingErrorOnChattyLevel) { - verbosity = lvlChatty; + verbosity = Verbosity::Chatty; testing::internal::CaptureStderr(); - logger->logEI({ .level = lvlChatty, + logger->logEI({ .level = Verbosity::Chatty, .name = "Chatty name", }); @@ -128,11 +128,11 @@ namespace nix { } TEST(logEI, loggingErrorOnDebugLevel) { - verbosity = lvlDebug; + verbosity = Verbosity::Debug; testing::internal::CaptureStderr(); - logger->logEI({ .level = lvlDebug, + logger->logEI({ .level = Verbosity::Debug, .name = "Debug name", }); @@ -141,11 +141,11 @@ namespace nix { } TEST(logEI, loggingErrorOnVomitLevel) { - verbosity = lvlVomit; + verbosity = Verbosity::Vomit; testing::internal::CaptureStderr(); - logger->logEI({ .level = lvlVomit, + logger->logEI({ .level = Verbosity::Vomit, .name = "Vomit name", }); diff --git a/src/libutil/archive.cc b/src/libutil/archive.cc index 0291d682729..3416141cd9c 100644 --- a/src/libutil/archive.cc +++ b/src/libutil/archive.cc @@ -69,24 +69,24 @@ void SourceAccessor::dumpPath(const CanonPath & path, Sink & sink, PathFilter & /* If we're on a case-insensitive system like macOS, undo the case hack applied by restorePath(). */ StringMap unhacked; - for (auto & i : this_.readDirectory(path)) + for (auto & [filename, _] : this_.readDirectory(path)) if (archiveSettings.useCaseHack) { - std::string name(i.first); - size_t pos = i.first.find(caseHackSuffix); + std::string name(filename); + size_t pos = filename.find(caseHackSuffix); if (pos != std::string::npos) { - debug("removing case hack suffix from '%s'", path / i.first); + debug("removing case hack suffix from '%s'", path / filename); name.erase(pos); } - if (!unhacked.emplace(name, i.first).second) + if (!unhacked.emplace(name, filename).second) throw Error( - "file name collision between '%s' and '%s'", (path / unhacked[name]), (path / i.first)); + "file name collision between '%s' and '%s'", (path / unhacked[name]), (path / filename)); } else - unhacked.emplace(i.first, i.first); + unhacked.emplace(filename, filename); - for (auto & i : unhacked) - if (filter((path / i.first).abs())) { - sink << "entry" << "(" << "name" << i.first << "node"; - dump(path / i.second); + for (auto & [displayName, actualName] : unhacked) + if (filter((path / displayName).abs())) { + sink << "entry" << "(" << "name" << displayName << "node"; + dump(path / actualName); sink << ")"; } } diff --git a/src/libutil/args.cc b/src/libutil/args.cc index c6d450a0bc6..8ccbe5f52b2 100644 --- a/src/libutil/args.cc +++ b/src/libutil/args.cc @@ -276,7 +276,7 @@ void RootArgs::parseCmdline(const Strings & _cmdline, bool allowShebang) assert(n > 0 && n <= cmdline.size()); *std::next(cmdline.begin(), n - 1) += completionMarker; completions = std::make_shared(); - verbosity = lvlError; + verbosity = Verbosity::Error; } // Heuristic to see if we're invoked as a shebang script, namely, @@ -312,8 +312,8 @@ void RootArgs::parseCmdline(const Strings & _cmdline, bool allowShebang) } cmdline.push_back(script); commandBaseDir = dirOf(script); - for (auto pos = savedArgs.begin(); pos != savedArgs.end(); pos++) - cmdline.push_back(*pos); + for (auto & arg : savedArgs) + cmdline.push_back(arg); } } catch (SystemError &) { } diff --git a/src/libutil/base-n.cc b/src/libutil/base-n.cc index 4c9726ad2e5..1c5f0c2ceae 100644 --- a/src/libutil/base-n.cc +++ b/src/libutil/base-n.cc @@ -8,7 +8,7 @@ using namespace std::literals; namespace nix { -constexpr static const std::array base16Chars = "0123456789abcdef"_arrayNoNull; +static constexpr std::array base16Chars = "0123456789abcdef"_arrayNoNull; std::string base16::encode(std::span b) { @@ -46,7 +46,7 @@ std::string base16::decode(std::string_view s) return res; } -constexpr static const std::array base64Chars = +static constexpr std::array base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"_arrayNoNull; std::string base64::encode(std::span s) diff --git a/src/libutil/canon-path.cc b/src/libutil/canon-path.cc index 22ca3e066a9..4cd09cae265 100644 --- a/src/libutil/canon-path.cc +++ b/src/libutil/canon-path.cc @@ -40,7 +40,7 @@ CanonPath::CanonPath(std::string_view raw, const CanonPath & root) ensureNoNullBytes(raw); } -CanonPath::CanonPath(const std::vector & elems) +CanonPath::CanonPath(std::span elems) : path("/") { for (auto & s : elems) diff --git a/src/libutil/compression.cc b/src/libutil/compression.cc index 36b476e9ad5..edb12f3f14a 100644 --- a/src/libutil/compression.cc +++ b/src/libutil/compression.cc @@ -8,6 +8,7 @@ #include #include #include +#include #include #include @@ -293,7 +294,7 @@ ref makeCompressionSink(const std::string & method, Sink & next { std::vector la_supports = { "bzip2", "compress", "grzip", "gzip", "lrzip", "lz4", "lzip", "lzma", "lzop", "xz", "zstd"}; - if (std::find(la_supports.begin(), la_supports.end(), method) != la_supports.end()) { + if (std::ranges::contains(la_supports, method)) { return make_ref(nextSink, method, parallel, level); } if (method == "none") diff --git a/src/libutil/config-global.cc b/src/libutil/config-global.cc index b63b4aaa1bb..064778fc9ce 100644 --- a/src/libutil/config-global.cc +++ b/src/libutil/config-global.cc @@ -46,8 +46,8 @@ std::string GlobalConfig::toKeyValue() std::string res; std::map settings; globalConfig.getSettings(settings); - for (const auto & s : settings) - res += fmt("%s = %s\n", s.first, s.second.value); + for (const auto & [name, info] : settings) + res += fmt("%s = %s\n", name, info.value); return res; } diff --git a/src/libutil/configuration.cc b/src/libutil/configuration.cc index 7a0ed22eae0..ca2cf1bf735 100644 --- a/src/libutil/configuration.cc +++ b/src/libutil/configuration.cc @@ -9,6 +9,7 @@ #include "nix/util/config-impl.hh" #include +#include #include "nix/util/strings.hh" @@ -73,24 +74,24 @@ AbstractConfig::AbstractConfig(StringMap initials) void AbstractConfig::warnUnknownSettings() { - for (const auto & s : unknownSettings) - warn("unknown setting '%s'", s.first); + for (const auto & [name, _] : unknownSettings) + warn("unknown setting '%s'", name); } void AbstractConfig::reapplyUnknownSettings() { auto unknownSettings2 = std::move(unknownSettings); unknownSettings = {}; - for (auto & s : unknownSettings2) - set(s.first, s.second); + for (auto & [name, value] : unknownSettings2) + set(name, value); } void Config::getSettings(std::map & res, bool overriddenOnly) const { - for (const auto & opt : _settings) - if (!opt.second.isAlias && (!overriddenOnly || opt.second.setting->overridden) - && experimentalFeatureSettings.isEnabled(opt.second.setting->experimentalFeature)) - res.emplace(opt.first, SettingInfo{opt.second.setting->to_string(), opt.second.setting->description}); + for (const auto & [name, data] : _settings) + if (!data.isAlias && (!overriddenOnly || data.setting->overridden) + && experimentalFeatureSettings.isEnabled(data.setting->experimentalFeature)) + res.emplace(name, SettingInfo{data.setting->to_string(), data.setting->description}); } /** @@ -192,33 +193,33 @@ void AbstractConfig::applyConfig(const std::string & contents, const std::string void Config::resetOverridden() { - for (auto & s : _settings) - s.second.setting->overridden = false; + for (auto & [_, data] : _settings) + data.setting->overridden = false; } nlohmann::json Config::toJSON() { auto res = nlohmann::json::object(); - for (const auto & s : _settings) - if (!s.second.isAlias) - res.emplace(s.first, s.second.setting->toJSON()); + for (const auto & [name, data] : _settings) + if (!data.isAlias) + res.emplace(name, data.setting->toJSON()); return res; } std::string Config::toKeyValue() { std::string res; - for (const auto & s : _settings) - if (s.second.isAlias) - res += fmt("%s = %s\n", s.first, s.second.setting->to_string()); + for (const auto & [name, data] : _settings) + if (data.isAlias) + res += fmt("%s = %s\n", name, data.setting->to_string()); return res; } void Config::convertToArgs(Args & args, const std::string & category) { - for (auto & s : _settings) { - if (!s.second.isAlias) - s.second.setting->convertToArg(args, category); + for (auto & [_, data] : _settings) { + if (!data.isAlias) + data.setting->convertToArg(args, category); } } @@ -430,7 +431,10 @@ std::string BaseSetting::to_string() const value.cend(), std::string{}, [](const auto & l, const auto & r) { return l + " " + r; }, - [](const auto & kvpair) { return kvpair.first + "=" + kvpair.second; }); + [](const auto & kv) { + auto & [key, val] = kv; + return key + "=" + val; + }); } template class BaseSetting; @@ -497,7 +501,7 @@ void OptionalPathSetting::operator=(const std::optional & v) bool ExperimentalFeatureSettings::isEnabled(const ExperimentalFeature & feature) const { auto & f = experimentalFeatures.get(); - return std::find(f.begin(), f.end(), feature) != f.end(); + return std::ranges::contains(f, feature); } void ExperimentalFeatureSettings::require(const ExperimentalFeature & feature, std::string reason) const diff --git a/src/libutil/current-process.cc b/src/libutil/current-process.cc index 5c48a4f7770..6d50d5f5aa2 100644 --- a/src/libutil/current-process.cc +++ b/src/libutil/current-process.cc @@ -49,7 +49,7 @@ unsigned int getMaxCPU() if (quota != "max") return std::ceil(std::stoi(quota) / std::stof(period)); } catch (Error &) { - ignoreExceptionInDestructor(lvlDebug); + ignoreExceptionInDestructor(Verbosity::Debug); } #endif @@ -69,7 +69,7 @@ void setStackSize(size_t stackSize) if (limit.rlim_max < static_cast(stackSize)) { if (getEnv("_NIX_TEST_NO_ENVIRONMENT_WARNINGS") != "1") { logger->log( - lvlWarn, + Verbosity::Warn, HintFmt( "Stack size hard limit is %1%, which is less than the desired %2%. If possible, increase the hard limit, e.g. with 'ulimit -Hs %3%'.", limit.rlim_max, @@ -82,7 +82,7 @@ void setStackSize(size_t stackSize) limit.rlim_cur = requestedSize; if (setrlimit(RLIMIT_STACK, &limit) != 0) { logger->log( - lvlError, + Verbosity::Error, HintFmt( "Failed to increase stack size from %1% to %2% (desired: %3%, maximum allowed: %4%): %5%", savedStackSize, diff --git a/src/libutil/environment-variables.cc b/src/libutil/environment-variables.cc index f2f24f7be10..9a5ecbd3a20 100644 --- a/src/libutil/environment-variables.cc +++ b/src/libutil/environment-variables.cc @@ -37,15 +37,15 @@ StringMap getEnv() void clearEnv() { - for (auto & name : getEnv()) - unsetenv(name.first.c_str()); + for (auto & [name, _] : getEnv()) + unsetenv(name.c_str()); } void replaceEnv(const StringMap & newEnv) { clearEnv(); - for (auto & newEnvVar : newEnv) - setEnv(newEnvVar.first.c_str(), newEnvVar.second.c_str()); + for (auto & [name, value] : newEnv) + setEnv(name.c_str(), value.c_str()); } } // namespace nix diff --git a/src/libutil/error.cc b/src/libutil/error.cc index 35e42823ce6..221e3b4a098 100644 --- a/src/libutil/error.cc +++ b/src/libutil/error.cc @@ -211,38 +211,38 @@ std::ostream & showErrorInfo(std::ostream & out, const ErrorInfo & einfo, bool s { std::string prefix; switch (einfo.level) { - case Verbosity::lvlError: { + case Verbosity::Error: { prefix = ANSI_RED "error"; break; } - case Verbosity::lvlNotice: { + case Verbosity::Notice: { prefix = ANSI_RED "note"; break; } - case Verbosity::lvlWarn: { + case Verbosity::Warn: { if (einfo.isFromExpr) prefix = ANSI_WARNING "evaluation warning"; else prefix = ANSI_WARNING "warning"; break; } - case Verbosity::lvlInfo: { + case Verbosity::Info: { prefix = ANSI_GREEN "info"; break; } - case Verbosity::lvlTalkative: { + case Verbosity::Talkative: { prefix = ANSI_GREEN "talk"; break; } - case Verbosity::lvlChatty: { + case Verbosity::Chatty: { prefix = ANSI_GREEN "chat"; break; } - case Verbosity::lvlVomit: { + case Verbosity::Vomit: { prefix = ANSI_GREEN "vomit"; break; } - case Verbosity::lvlDebug: { + case Verbosity::Debug: { prefix = ANSI_WARNING "debug"; break; } diff --git a/src/libutil/executable-path.cc b/src/libutil/executable-path.cc index 75ab91f3a16..d3a148f5efd 100644 --- a/src/libutil/executable-path.cc +++ b/src/libutil/executable-path.cc @@ -6,7 +6,7 @@ namespace nix { -constexpr static const OsStringView path_var_separator{ +static constexpr OsStringView path_var_separator{ &ExecutablePath::separator, 1, }; diff --git a/src/libutil/file-system.cc b/src/libutil/file-system.cc index 758173f4169..2238f0c099f 100644 --- a/src/libutil/file-system.cc +++ b/src/libutil/file-system.cc @@ -583,7 +583,7 @@ void createDirs(const std::filesystem::path & path) void deletePath(const std::filesystem::path & path, uint64_t & bytesFreed) { - // Activity act(*logger, lvlDebug, "recursively deleting path '%1%'", path); + // Activity act(*logger, Verbosity::Debug, "recursively deleting path '%1%'", path); #ifdef __FreeBSD__ std::set mountedPaths; struct statfs * mntbuf; diff --git a/src/libutil/hash.cc b/src/libutil/hash.cc index 56eed931bed..c8c2b4d7fdd 100644 --- a/src/libutil/hash.cc +++ b/src/libutil/hash.cc @@ -301,7 +301,7 @@ static void start(HashAlgorithm ha, Hash::Ctx & ctx) // // NOTE: This threshold is based on the recommended rule-of-thumb from the official BLAKE3 documentation for typical // x86_64 hardware as of 2025. In the future it may make sense to allow the user to tune this through nix.conf. -const size_t blake3TbbThreshold = 128000; +constexpr size_t blake3TbbThreshold = 128000; // Decide which BLAKE3 update strategy to use based on some heuristics. Currently this just checks the data size but in // the future it might also take into consideration available system resources or the presence of a shared-memory diff --git a/src/libutil/hilite.cc b/src/libutil/hilite.cc index 8b7e3ff2368..2fbd76ba35e 100644 --- a/src/libutil/hilite.cc +++ b/src/libutil/hilite.cc @@ -1,5 +1,7 @@ #include "nix/util/hilite.hh" +#include + namespace nix { std::string @@ -9,8 +11,7 @@ hiliteMatches(std::string_view s, std::vector matches, std::string_ if (matches.size() == 0) return std::string(s); - std::sort( - matches.begin(), matches.end(), [](const auto & a, const auto & b) { return a.position() < b.position(); }); + std::ranges::sort(matches, [](const auto & a, const auto & b) { return a.position() < b.position(); }); std::string out; ssize_t last_end = 0; diff --git a/src/libutil/include/nix/util/args.hh b/src/libutil/include/nix/util/args.hh index d793411247b..5559778aeaf 100644 --- a/src/libutil/include/nix/util/args.hh +++ b/src/libutil/include/nix/util/args.hh @@ -68,7 +68,7 @@ protected: * handlers/flags/arguments that accept an arbitrary number of * arguments. */ - static const size_t ArityAny = std::numeric_limits::max(); + static constexpr size_t ArityAny = std::numeric_limits::max(); /** * Arguments (flags/options and positional) have a "handler" which is diff --git a/src/libutil/include/nix/util/base-nix-32.hh b/src/libutil/include/nix/util/base-nix-32.hh index 28095e92c82..2db0cef184c 100644 --- a/src/libutil/include/nix/util/base-nix-32.hh +++ b/src/libutil/include/nix/util/base-nix-32.hh @@ -19,7 +19,7 @@ struct BaseNix32 private: static const std::array reverseMap; - const static constexpr uint8_t invalid = 0xFF; + static constexpr uint8_t invalid = 0xFF; public: static inline std::optional lookupReverse(char base32) @@ -34,7 +34,7 @@ public: /** * Returns the length of a base-32 representation of this hash. */ - [[nodiscard]] constexpr static inline size_t encodedLength(size_t originalLength) + [[nodiscard]] static constexpr size_t encodedLength(size_t originalLength) { return (originalLength * 8 - 1) / 5 + 1; } diff --git a/src/libutil/include/nix/util/canon-path.hh b/src/libutil/include/nix/util/canon-path.hh index 2156b02fc41..a82f164fb96 100644 --- a/src/libutil/include/nix/util/canon-path.hh +++ b/src/libutil/include/nix/util/canon-path.hh @@ -7,6 +7,7 @@ #include #include #include +#include #include #include @@ -68,9 +69,9 @@ public: } /** - * Construct a canon path from a vector of elements. + * Construct a canon path from a span of elements. */ - CanonPath(const std::vector & elems); + CanonPath(std::span elems); static const CanonPath root; diff --git a/src/libutil/include/nix/util/error.hh b/src/libutil/include/nix/util/error.hh index cc8460592a2..f8f5eb6976c 100644 --- a/src/libutil/include/nix/util/error.hh +++ b/src/libutil/include/nix/util/error.hh @@ -30,7 +30,32 @@ namespace nix { -typedef enum { lvlError = 0, lvlWarn, lvlNotice, lvlInfo, lvlTalkative, lvlChatty, lvlDebug, lvlVomit } Verbosity; +enum class Verbosity { + Error = 0, + Warn, + Notice, + Info, + Talkative, + Chatty, + Debug, + Vomit, +}; + +/// Increment verbosity, clamping at Vomit +constexpr Verbosity & operator++(Verbosity & v) +{ + if (v != Verbosity::Vomit) + v = static_cast(static_cast(v) + 1); + return v; +} + +/// Decrement verbosity, clamping at Error +constexpr Verbosity & operator--(Verbosity & v) +{ + if (v != Verbosity::Error) + v = static_cast(static_cast(v) - 1); + return v; +} /** * The lines of code surrounding an error. @@ -124,24 +149,24 @@ public: template BaseError(unsigned int status, const Args &... args) - : err{.level = lvlError, .msg = HintFmt(args...), .status = status} + : err{.level = Verbosity::Error, .msg = HintFmt(args...), .status = status} { } template explicit BaseError(const std::string & fs, const Args &... args) - : err{.level = lvlError, .msg = HintFmt(fs, args...)} + : err{.level = Verbosity::Error, .msg = HintFmt(fs, args...)} { } template BaseError(const Suggestions & sug, const Args &... args) - : err{.level = lvlError, .msg = HintFmt(args...), .suggestions = sug} + : err{.level = Verbosity::Error, .msg = HintFmt(args...), .suggestions = sug} { } BaseError(HintFmt hint) - : err{.level = lvlError, .msg = hint} + : err{.level = Verbosity::Error, .msg = hint} { } diff --git a/src/libutil/include/nix/util/executable-path.hh b/src/libutil/include/nix/util/executable-path.hh index cf6f3b25200..feaa94dd1f1 100644 --- a/src/libutil/include/nix/util/executable-path.hh +++ b/src/libutil/include/nix/util/executable-path.hh @@ -15,7 +15,7 @@ struct ExecutablePath { std::vector directories; - constexpr static const OsChar separator = + static constexpr OsChar separator = #ifdef WIN32 L';' #else diff --git a/src/libutil/include/nix/util/exit.hh b/src/libutil/include/nix/util/exit.hh index 5f0f256edd0..94825603d93 100644 --- a/src/libutil/include/nix/util/exit.hh +++ b/src/libutil/include/nix/util/exit.hh @@ -10,12 +10,9 @@ namespace nix { class Exit : public std::exception { public: - int status; + int status = 0; - Exit() - : status(0) - { - } + Exit() = default; explicit Exit(int status) : status(status) diff --git a/src/libutil/include/nix/util/file-descriptor.hh b/src/libutil/include/nix/util/file-descriptor.hh index d049845883c..e0bcfe417cf 100644 --- a/src/libutil/include/nix/util/file-descriptor.hh +++ b/src/libutil/include/nix/util/file-descriptor.hh @@ -26,7 +26,7 @@ using Descriptor = #endif ; -const Descriptor INVALID_DESCRIPTOR = +constexpr Descriptor INVALID_DESCRIPTOR = #ifdef _WIN32 INVALID_HANDLE_VALUE #else diff --git a/src/libutil/include/nix/util/file-path-impl.hh b/src/libutil/include/nix/util/file-path-impl.hh index 91c1a58cd0b..df0bc68354d 100644 --- a/src/libutil/include/nix/util/file-path-impl.hh +++ b/src/libutil/include/nix/util/file-path-impl.hh @@ -26,17 +26,17 @@ struct UnixPathTrait constexpr static char preferredSep = '/'; - static inline bool isPathSep(char c) + static constexpr bool isPathSep(char c) { return c == '/'; } - static inline size_t findPathSep(StringView path, size_t from = 0) + static constexpr size_t findPathSep(StringView path, size_t from = 0) { return path.find('/', from); } - static inline size_t rfindPathSep(StringView path, size_t from = StringView::npos) + static constexpr size_t rfindPathSep(StringView path, size_t from = StringView::npos) { return path.rfind('/', from); } @@ -65,19 +65,19 @@ struct WindowsPathTrait constexpr static CharT preferredSep = '\\'; - static inline bool isPathSep(CharT c) + static constexpr bool isPathSep(CharT c) { return c == '/' || c == preferredSep; } - static size_t findPathSep(StringView path, size_t from = 0) + static constexpr size_t findPathSep(StringView path, size_t from = 0) { size_t p1 = path.find('/', from); size_t p2 = path.find(preferredSep, from); return p1 == String::npos ? p2 : p2 == String::npos ? p1 : std::min(p1, p2); } - static size_t rfindPathSep(StringView path, size_t from = String::npos) + static constexpr size_t rfindPathSep(StringView path, size_t from = String::npos) { size_t p1 = path.rfind('/', from); size_t p2 = path.rfind(preferredSep, from); diff --git a/src/libutil/include/nix/util/hash.hh b/src/libutil/include/nix/util/hash.hh index e4f59609109..6c4f7a93777 100644 --- a/src/libutil/include/nix/util/hash.hh +++ b/src/libutil/include/nix/util/hash.hh @@ -145,12 +145,12 @@ public: /** * Helper that defaults empty hashes to the 0 hash. */ -Hash newHashAllowEmpty(std::string_view hashStr, std::optional ha); +[[nodiscard]] Hash newHashAllowEmpty(std::string_view hashStr, std::optional ha); /** * Compute the hash of the given string. */ -Hash hashString( +[[nodiscard]] Hash hashString( HashAlgorithm ha, std::string_view s, const ExperimentalFeatureSettings & xpSettings = experimentalFeatureSettings); /** @@ -158,7 +158,7 @@ Hash hashString( * * (Metadata, such as the executable permission bit, is ignored.) */ -Hash hashFile(HashAlgorithm ha, const Path & path); +[[nodiscard]] Hash hashFile(HashAlgorithm ha, const Path & path); /** * The final hash and the number of bytes digested. @@ -173,39 +173,39 @@ struct HashResult * Compress a hash to the specified number of bytes by cyclically * XORing bytes together. */ -Hash compressHash(const Hash & hash, unsigned int newSize); +[[nodiscard]] Hash compressHash(const Hash & hash, unsigned int newSize); /** * Parse a string representing a hash format. */ -HashFormat parseHashFormat(std::string_view hashFormatName); +[[nodiscard]] HashFormat parseHashFormat(std::string_view hashFormatName); /** * std::optional version of parseHashFormat that doesn't throw error. */ -std::optional parseHashFormatOpt(std::string_view hashFormatName); +[[nodiscard]] std::optional parseHashFormatOpt(std::string_view hashFormatName); /** * The reverse of parseHashFormat. */ -std::string_view printHashFormat(HashFormat hashFormat); +[[nodiscard]] std::string_view printHashFormat(HashFormat hashFormat); /** * Parse a string representing a hash algorithm. */ -HashAlgorithm +[[nodiscard]] HashAlgorithm parseHashAlgo(std::string_view s, const ExperimentalFeatureSettings & xpSettings = experimentalFeatureSettings); /** * Will return nothing on parse error */ -std::optional +[[nodiscard]] std::optional parseHashAlgoOpt(std::string_view s, const ExperimentalFeatureSettings & xpSettings = experimentalFeatureSettings); /** * And the reverse. */ -std::string_view printHashAlgo(HashAlgorithm ha); +[[nodiscard]] std::string_view printHashAlgo(HashAlgorithm ha); struct AbstractHashSink : virtual Sink { diff --git a/src/libutil/include/nix/util/logging.hh b/src/libutil/include/nix/util/logging.hh index 500d443e6e2..ec2d518268f 100644 --- a/src/libutil/include/nix/util/logging.hh +++ b/src/libutil/include/nix/util/logging.hh @@ -12,34 +12,34 @@ namespace nix { -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, - actFetchTree = 112, -} ActivityType; - -typedef enum { - resFileLinked = 100, - resBuildLogLine = 101, - resUntrustedPath = 102, - resCorruptedPath = 103, - resSetPhase = 104, - resProgress = 105, - resSetExpected = 106, - resPostBuildLogLine = 107, - resFetchStatus = 108, -} ResultType; +enum class ActivityType { + Unknown = 0, + CopyPath = 100, + FileTransfer = 101, + Realise = 102, + CopyPaths = 103, + Builds = 104, + Build = 105, + OptimiseStore = 106, + VerifyPaths = 107, + Substitute = 108, + QueryPathInfo = 109, + PostBuildHook = 110, + BuildWaiting = 111, + FetchTree = 112, +}; + +enum class ResultType { + FileLinked = 100, + BuildLogLine = 101, + UntrustedPath = 102, + CorruptedPath = 103, + SetPhase = 104, + Progress = 105, + SetExpected = 106, + PostBuildLogLine = 107, + FetchStatus = 108, +}; typedef uint64_t ActivityId; @@ -78,28 +78,35 @@ public: struct Field { // FIXME: use std::variant. - enum { tInt = 0, tString = 1 } type; + enum class Type { Int = 0, String = 1 }; + Type type; uint64_t i = 0; std::string s; Field(const std::string & s) - : type(tString) + : type(Type::String) , s(s) { } Field(const char * s) - : type(tString) + : type(Type::String) , s(s) { } Field(const uint64_t & i) - : type(tInt) + : type(Type::Int) , i(i) { } + + Field(const ActivityType & a) + : type(Type::Int) + , i(static_cast(a)) + { + } }; typedef std::vector Fields; @@ -133,7 +140,7 @@ public: void log(std::string_view s) { - log(lvlInfo, s); + log(Verbosity::Info, s); } virtual void logEI(const ErrorInfo & ei) = 0; @@ -206,7 +213,7 @@ 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; @@ -214,12 +221,12 @@ struct 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, type2, expected); } template @@ -315,8 +322,8 @@ extern Verbosity verbosity; } \ } while (0) -#define logError(errorInfo...) logErrorInfo(lvlError, errorInfo) -#define logWarning(errorInfo...) logErrorInfo(lvlWarn, errorInfo) +#define logError(errorInfo...) logErrorInfo(Verbosity::Error, errorInfo) +#define logWarning(errorInfo...) logErrorInfo(Verbosity::Warn, errorInfo) /** * Print a string message if the current log level is at least the specified @@ -332,15 +339,15 @@ extern Verbosity verbosity; } while (0) #define printMsg(level, args...) printMsgUsing(logger, level, args) -#define printError(args...) printMsg(lvlError, args) -#define notice(args...) printMsg(lvlNotice, 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 notice(args...) printMsg(Verbosity::Notice, 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) /** - * if verbosity >= lvlWarn, print a message with a yellow 'warning:' prefix. + * if verbosity >= Verbosity::Warn, print a message with a yellow 'warning:' prefix. */ template inline void warn(const std::string & fs, const Args &... args) diff --git a/src/libutil/include/nix/util/pos-idx.hh b/src/libutil/include/nix/util/pos-idx.hh index 8e668176c61..806ef7694a5 100644 --- a/src/libutil/include/nix/util/pos-idx.hh +++ b/src/libutil/include/nix/util/pos-idx.hh @@ -13,7 +13,7 @@ class PosIdx friend class std::hash; private: - uint32_t id; + uint32_t id = 0; explicit PosIdx(uint32_t id) : id(id) @@ -21,10 +21,7 @@ private: } public: - PosIdx() - : id(0) - { - } + PosIdx() = default; explicit operator bool() const { diff --git a/src/libutil/include/nix/util/ref.hh b/src/libutil/include/nix/util/ref.hh index 7ba5349a60b..830e38791c0 100644 --- a/src/libutil/include/nix/util/ref.hh +++ b/src/libutil/include/nix/util/ref.hh @@ -113,7 +113,7 @@ private: }; template -inline ref make_ref(Args &&... args) +[[nodiscard]] inline ref make_ref(Args &&... args) { auto p = std::make_shared(std::forward(args)...); return ref(p); diff --git a/src/libutil/include/nix/util/serialise.hh b/src/libutil/include/nix/util/serialise.hh index 5db55c60dbb..8a48b5f64d0 100644 --- a/src/libutil/include/nix/util/serialise.hh +++ b/src/libutil/include/nix/util/serialise.hh @@ -123,7 +123,7 @@ struct BufferedSource : Source /** * Return true if the buffer is not empty. */ - bool hasData(); + bool hasData() const; protected: /** @@ -201,7 +201,7 @@ struct FdSource : BufferedSource * Return true if the buffer is not empty after a non-blocking * read. */ - bool hasData(); + bool hasData() const; void skip(size_t len) override; diff --git a/src/libutil/include/nix/util/source-accessor.hh b/src/libutil/include/nix/util/source-accessor.hh index 1006895b33c..5cdf79a05d2 100644 --- a/src/libutil/include/nix/util/source-accessor.hh +++ b/src/libutil/include/nix/util/source-accessor.hh @@ -117,8 +117,8 @@ struct SourceAccessor : std::enable_shared_from_this */ std::optional narOffset; - bool isNotNARSerialisable(); - std::string typeString(); + bool isNotNARSerialisable() const; + std::string typeString() const; }; virtual Stat lstat(const CanonPath & path); diff --git a/src/libutil/include/nix/util/url.hh b/src/libutil/include/nix/util/url.hh index 55c475df651..437359548f6 100644 --- a/src/libutil/include/nix/util/url.hh +++ b/src/libutil/include/nix/util/url.hh @@ -265,7 +265,7 @@ std::string percentEncode(std::string_view s, std::string_view keep = ""); * paths have no escape sequences --- file names cannot contain a * `/`. */ -Path renderUrlPathEnsureLegal(const std::vector & urlPath); +Path renderUrlPathEnsureLegal(std::span urlPath); /** * Percent encode path. `%2F` for "interior slashes" is the most diff --git a/src/libutil/include/nix/util/util.hh b/src/libutil/include/nix/util/util.hh index 7556663cd1d..b93fb5a35df 100644 --- a/src/libutil/include/nix/util/util.hh +++ b/src/libutil/include/nix/util/util.hh @@ -216,7 +216,7 @@ std::string escapeShellArgAlways(const std::string_view s); * but ideally we propagate the exception using an exception_ptr in such cases. * See e.g. `PackBuilderContext` */ -void ignoreExceptionInDestructor(Verbosity lvl = lvlError); +void ignoreExceptionInDestructor(Verbosity lvl = Verbosity::Error); /** * Not destructor-safe. @@ -225,7 +225,7 @@ void ignoreExceptionInDestructor(Verbosity lvl = lvlError); * * This may be used in a few places where Interrupt can't happen, but that's ok. */ -void ignoreExceptionExceptInterrupt(Verbosity lvl = lvlError); +void ignoreExceptionExceptInterrupt(Verbosity lvl = Verbosity::Error); /** * Tree formatting. diff --git a/src/libutil/logging.cc b/src/libutil/logging.cc index e2f28f553a4..3b5d1c09bc2 100644 --- a/src/libutil/logging.cc +++ b/src/libutil/logging.cc @@ -36,7 +36,7 @@ std::unique_ptr logger = makeSimpleLogger(true); void Logger::warn(const std::string & msg) { - log(lvlWarn, ANSI_WARNING "warning:" ANSI_NORMAL " " + msg); + log(Verbosity::Warn, ANSI_WARNING "warning:" ANSI_NORMAL " " + msg); } void Logger::writeToStdout(std::string_view s) @@ -88,22 +88,22 @@ class SimpleLogger : public Logger if (systemd) { char c; switch (lvl) { - case lvlError: + case Verbosity::Error: c = '3'; break; - case lvlWarn: + case Verbosity::Warn: c = '4'; break; - case lvlNotice: - case lvlInfo: + case Verbosity::Notice: + case Verbosity::Info: c = '5'; break; - case lvlTalkative: - case lvlChatty: + case Verbosity::Talkative: + case Verbosity::Chatty: c = '6'; break; - case lvlDebug: - case lvlVomit: + case Verbosity::Debug: + case Verbosity::Vomit: c = '7'; break; default: @@ -138,17 +138,17 @@ class SimpleLogger : public Logger void result(ActivityId act, ResultType type, const Fields & fields) override { - if (type == resBuildLogLine && printBuildLogs) { + if (type == ResultType::BuildLogLine && printBuildLogs) { auto lastLine = fields[0].s; printError(lastLine); - } else if (type == resPostBuildLogLine && printBuildLogs) { + } else if (type == ResultType::PostBuildLogLine && printBuildLogs) { auto lastLine = fields[0].s; printError("post-build-hook: " + lastLine); } } }; -Verbosity verbosity = lvlInfo; +Verbosity verbosity = Verbosity::Info; void writeToStderr(std::string_view s) { @@ -228,9 +228,9 @@ struct JSONLogger : Logger return; auto & arr = json["fields"] = nlohmann::json::array(); for (auto & f : fields) - if (f.type == Logger::Field::tInt) + if (f.type == Logger::Field::Type::Int) arr.push_back(f.i); - else if (f.type == Logger::Field::tString) + else if (f.type == Logger::Field::Type::String) arr.push_back(f.s); else unreachable(); @@ -421,7 +421,7 @@ bool handleJSONLogMessage( if (action == "start") { auto type = (ActivityType) json["type"]; - if (trusted || type == actFileTransfer) + if (trusted || type == ActivityType::FileTransfer) activities.emplace( std::piecewise_construct, std::forward_as_tuple(json["id"]), @@ -440,7 +440,7 @@ bool handleJSONLogMessage( 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/nar-accessor.cc b/src/libutil/nar-accessor.cc index 22b6abdd581..cfb1f4ab7f0 100644 --- a/src/libutil/nar-accessor.cc +++ b/src/libutil/nar-accessor.cc @@ -206,8 +206,8 @@ struct NarAccessor : public SourceAccessor throw Error("path '%1%' inside NAR file is not a directory", path); DirEntries res; - for (const auto & child : i.children) - res.insert_or_assign(child.first, std::nullopt); + for (const auto & [name, _] : i.children) + res.insert_or_assign(name, std::nullopt); return res; } diff --git a/src/libutil/serialise.cc b/src/libutil/serialise.cc index fea31fbb6b9..2949aabd9dc 100644 --- a/src/libutil/serialise.cc +++ b/src/libutil/serialise.cc @@ -138,7 +138,7 @@ size_t BufferedSource::read(char * data, size_t len) return n; } -bool BufferedSource::hasData() +bool BufferedSource::hasData() const { return bufPosOut < bufPosIn; } @@ -176,7 +176,7 @@ bool FdSource::good() return _good; } -bool FdSource::hasData() +bool FdSource::hasData() const { if (BufferedSource::hasData()) return true; @@ -424,8 +424,8 @@ Sink & operator<<(Sink & sink, const StringSet & s) Sink & operator<<(Sink & sink, const Error & ex) { auto & info = ex.info(); - sink << "Error" << info.level << "Error" // removed - << info.msg.str() << 0 // FIXME: info.errPos + sink << "Error" << static_cast(info.level) << "Error" // removed + << info.msg.str() << 0 // FIXME: info.errPos << info.traces.size(); for (auto & trace : info.traces) { sink << 0; // FIXME: trace.pos diff --git a/src/libutil/source-accessor.cc b/src/libutil/source-accessor.cc index 3c2d658290c..f7913f33e44 100644 --- a/src/libutil/source-accessor.cc +++ b/src/libutil/source-accessor.cc @@ -5,12 +5,12 @@ namespace nix { static std::atomic nextNumber{0}; -bool SourceAccessor::Stat::isNotNARSerialisable() +bool SourceAccessor::Stat::isNotNARSerialisable() const { return this->type != tRegular && this->type != tSymlink && this->type != tDirectory; } -std::string SourceAccessor::Stat::typeString() +std::string SourceAccessor::Stat::typeString() const { switch (this->type) { case tRegular: diff --git a/src/libutil/url.cc b/src/libutil/url.cc index 0a8b6452814..64a4b17ff65 100644 --- a/src/libutil/url.cc +++ b/src/libutil/url.cc @@ -321,7 +321,7 @@ std::string encodeQuery(const StringMap & ss) return res; } -Path renderUrlPathEnsureLegal(const std::vector & urlPath) +Path renderUrlPathEnsureLegal(std::span urlPath) { for (const auto & comp : urlPath) { /* This is only really valid for UNIX. Windows has more restrictions. */ diff --git a/src/libutil/util.cc b/src/libutil/util.cc index d75aa4d67d9..dacacc027ac 100644 --- a/src/libutil/util.cc +++ b/src/libutil/util.cc @@ -85,12 +85,12 @@ std::string replaceStrings(std::string res, std::string_view from, std::string_v std::string rewriteStrings(std::string s, const StringMap & rewrites) { - for (auto & i : rewrites) { - if (i.first == i.second) + for (auto & [from, to] : rewrites) { + if (from == to) continue; size_t j = 0; - while ((j = s.find(i.first, j)) != s.npos) - s.replace(j, i.first.size(), i.second); + while ((j = s.find(from, j)) != s.npos) + s.replace(j, from.size(), to); } return s; } diff --git a/src/libutil/windows/muxable-pipe.cc b/src/libutil/windows/muxable-pipe.cc index b2eff70e611..b6873064d38 100644 --- a/src/libutil/windows/muxable-pipe.cc +++ b/src/libutil/windows/muxable-pipe.cc @@ -34,7 +34,7 @@ void MuxablePipePollState::iterate( ++nextp; for (ULONG i = 0; i < removed; i++) { if (oentries[i].lpCompletionKey == ((ULONG_PTR) ((*p)->readSide.get()) ^ 0x5555)) { - printMsg(lvlVomit, "read %s bytes", oentries[i].dwNumberOfBytesTransferred); + printMsg(Verbosity::Vomit, "read %s bytes", oentries[i].dwNumberOfBytesTransferred); if (oentries[i].dwNumberOfBytesTransferred > 0) { std::string data{ (char *) (*p)->buffer.data(), diff --git a/src/libutil/windows/processes.cc b/src/libutil/windows/processes.cc index f8f2900e55d..41e36136870 100644 --- a/src/libutil/windows/processes.cc +++ b/src/libutil/windows/processes.cc @@ -214,13 +214,13 @@ Pid spawnProcess(const Path & realProgram, const RunOptions & options, Pipe & ou std::string envline; // Retain the current processes' environment variables. - for (const auto & envVar : getEnv()) { - envline += (envVar.first + '=' + envVar.second + '\0'); + for (const auto & [name, value] : getEnv()) { + envline += (name + '=' + value + '\0'); } // Also add new ones specified in options. if (options.environment) { - for (const auto & envVar : *options.environment) { - envline += (envVar.first + '=' + envVar.second + '\0'); + for (const auto & [name, value] : *options.environment) { + envline += (name + '=' + value + '\0'); } } diff --git a/src/libutil/xml-writer.cc b/src/libutil/xml-writer.cc index 9b7ca969db4..a0df9914441 100644 --- a/src/libutil/xml-writer.cc +++ b/src/libutil/xml-writer.cc @@ -70,10 +70,10 @@ void XMLWriter::writeEmptyElement(std::string_view name, const XMLAttrs & attrs) void XMLWriter::writeAttrs(const XMLAttrs & attrs) { - for (auto & i : attrs) { - output << " " << i.first << "=\""; - for (size_t j = 0; j < i.second.size(); ++j) { - char c = i.second[j]; + for (auto & [name, value] : attrs) { + output << " " << name << "=\""; + for (size_t j = 0; j < value.size(); ++j) { + char c = value[j]; if (c == '"') output << """; else if (c == '<') diff --git a/src/nix/build-remote/build-remote.cc b/src/nix/build-remote/build-remote.cc index f62712d30ea..994e1b914d3 100644 --- a/src/nix/build-remote/build-remote.cc +++ b/src/nix/build-remote/build-remote.cc @@ -214,7 +214,7 @@ static int main_build_remote(int argc, char ** argv) % concatStringsSep(", ", m.supportedFeatures) % concatStringsSep(", ", m.mandatoryFeatures); - printMsg(couldBuildLocally ? lvlChatty : lvlWarn, error.str()); + printMsg(couldBuildLocally ? Verbosity::Chatty : Verbosity::Warn, error.str()); std::cerr << "# decline\n"; } @@ -232,7 +232,8 @@ static int main_build_remote(int argc, char ** argv) try { storeUri = bestMachine->storeUri.render(); - Activity act(*logger, lvlTalkative, actUnknown, fmt("connecting to '%s'", storeUri)); + Activity act( + *logger, Verbosity::Talkative, ActivityType::Unknown, fmt("connecting to '%s'", storeUri)); sshStore = bestMachine->openStore(); sshStore->connect(); @@ -274,7 +275,11 @@ static int main_build_remote(int argc, char ** argv) } { - Activity act(*logger, lvlTalkative, actUnknown, fmt("waiting for the upload lock to '%s'", storeUri)); + Activity act( + *logger, + Verbosity::Talkative, + ActivityType::Unknown, + fmt("waiting for the upload lock to '%s'", storeUri)); auto old = signal(SIGALRM, handleAlarm); alarm(15 * 60); @@ -287,7 +292,8 @@ static int main_build_remote(int argc, char ** argv) auto substitute = settings.buildersUseSubstitutes ? Substitute : NoSubstitute; { - Activity act(*logger, lvlTalkative, actUnknown, fmt("copying dependencies to '%s'", storeUri)); + Activity act( + *logger, Verbosity::Talkative, ActivityType::Unknown, fmt("copying dependencies to '%s'", storeUri)); copyPaths(*store, *sshStore, store->parseStorePathSet(inputs), NoRepair, NoCheckSigs, substitute); } @@ -377,7 +383,8 @@ static int main_build_remote(int argc, char ** argv) } if (!missingPaths.empty()) { - Activity act(*logger, lvlTalkative, actUnknown, fmt("copying outputs from '%s'", storeUri)); + Activity act( + *logger, Verbosity::Talkative, ActivityType::Unknown, fmt("copying outputs from '%s'", storeUri)); if (auto localStore = store.dynamic_pointer_cast()) for (auto & path : missingPaths) localStore->locksHeld.insert(store->printStorePath(path)); /* FIXME: ugly */ diff --git a/src/nix/build.cc b/src/nix/build.cc index 2d4f426a495..8a91175df85 100644 --- a/src/nix/build.cc +++ b/src/nix/build.cc @@ -147,7 +147,7 @@ struct CmdBuild : InstallablesCommand, MixOutLinkByDefault, MixDryRun, MixJSON, for (auto & b : i->toDerivedPaths()) pathsToBuild.push_back(b.path); - printMissing(store, pathsToBuild, lvlError); + printMissing(store, pathsToBuild, Verbosity::Error); if (json) printJSON(derivedPathsToJSON(pathsToBuild, *store)); diff --git a/src/nix/develop.cc b/src/nix/develop.cc index 68ff3fcf965..17dc4d1b87d 100644 --- a/src/nix/develop.cc +++ b/src/nix/develop.cc @@ -203,7 +203,8 @@ struct BuildEnvironment return *arr; } else if (auto assoc = std::get_if(&value)) { Array assocKeys; - std::for_each(assoc->begin(), assoc->end(), [&](auto & n) { assocKeys.push_back(n.first); }); + for (const auto & n : *assoc) + assocKeys.push_back(n.first); return assocKeys; } else throw Error("bash variable is not a string or array"); @@ -597,7 +598,7 @@ struct CmdDevelop : Common, MixEnvironment auto script = makeRcScript(store, buildEnvironment, tmpDir); - if (verbosity >= lvlDebug) + if (verbosity >= Verbosity::Debug) script += "set -x\n"; script += fmt("command rm -f '%s'\n", rcFilePath); diff --git a/src/nix/flake-prefetch-inputs.cc b/src/nix/flake-prefetch-inputs.cc index 4ea6342c369..f06622ab870 100644 --- a/src/nix/flake-prefetch-inputs.cc +++ b/src/nix/flake-prefetch-inputs.cc @@ -44,7 +44,8 @@ struct CmdFlakePrefetchInputs : FlakeCommand if (auto lockedNode = dynamic_cast(&node)) { try { - Activity act(*logger, lvlInfo, actUnknown, fmt("fetching '%s'", lockedNode->lockedRef)); + Activity act( + *logger, Verbosity::Info, ActivityType::Unknown, fmt("fetching '%s'", lockedNode->lockedRef)); auto accessor = lockedNode->lockedRef.input.getAccessor(fetchSettings, *store).first; fetchToStore( fetchSettings, *store, accessor, FetchMode::Copy, lockedNode->lockedRef.input.getName()); diff --git a/src/nix/flake.cc b/src/nix/flake.cc index be19b5317dd..ead09d823dd 100644 --- a/src/nix/flake.cc +++ b/src/nix/flake.cc @@ -271,16 +271,17 @@ struct CmdFlakeMetadata : FlakeCommand, MixJSON [&](this const auto & recurse, const Node & node, const std::string & prefix) -> void { for (const auto & [i, input] : enumerate(node.inputs)) { + auto & [inputName, inputValue] = input; bool last = i + 1 == node.inputs.size(); - if (auto lockedNode = std::get_if<0>(&input.second)) { + if (auto lockedNode = std::get_if<0>(&inputValue)) { std::string lastModifiedStr = ""; if (auto lastModified = (*lockedNode)->lockedRef.input.getLastModified()) lastModifiedStr = fmt(" (%s)", std::put_time(std::gmtime(&*lastModified), "%F %T")); logger->cout( "%s" ANSI_BOLD "%s" ANSI_NORMAL ": %s%s", prefix + (last ? treeLast : treeConn), - input.first, + inputName, (*lockedNode)->lockedRef, lastModifiedStr); @@ -288,11 +289,11 @@ struct CmdFlakeMetadata : FlakeCommand, MixJSON if (firstVisit) recurse(**lockedNode, prefix + (last ? treeNull : treeLine)); - } else if (auto follows = std::get_if<1>(&input.second)) { + } else if (auto follows = std::get_if<1>(&inputValue)) { logger->cout( "%s" ANSI_BOLD "%s" ANSI_NORMAL " follows input '%s'", prefix + (last ? treeLast : treeConn), - input.first, + inputName, printInputAttrPath(*follows)); } } @@ -398,7 +399,7 @@ struct CmdFlakeCheck : FlakeCommand auto checkDerivation = [&](const std::string & attrPath, Value & v, const PosIdx pos) -> std::optional { try { - Activity act(*logger, lvlInfo, actUnknown, fmt("checking derivation %s", attrPath)); + Activity act(*logger, Verbosity::Info, ActivityType::Unknown, fmt("checking derivation %s", attrPath)); auto packageInfo = getDerivation(*state, v, false); if (!packageInfo) throw Error("flake attribute '%s' is not a derivation", attrPath); @@ -407,7 +408,8 @@ struct CmdFlakeCheck : FlakeCommand auto storePath = packageInfo->queryDrvPath(); if (storePath) { logger->log( - lvlInfo, fmt("derivation evaluated to %s", store->printStorePath(storePath.value()))); + Verbosity::Info, + fmt("derivation evaluated to %s", store->printStorePath(storePath.value()))); } return storePath; } @@ -422,7 +424,7 @@ struct CmdFlakeCheck : FlakeCommand auto checkApp = [&](const std::string & attrPath, Value & v, const PosIdx pos) { try { - Activity act(*logger, lvlInfo, actUnknown, fmt("checking app '%s'", attrPath)); + Activity act(*logger, Verbosity::Info, ActivityType::Unknown, fmt("checking app '%s'", attrPath)); state->forceAttrs(v, pos, ""); if (auto attr = v.attrs()->get(state->symbols.create("type"))) state->forceStringNoCtx(*attr->value, attr->pos, ""); @@ -463,7 +465,7 @@ struct CmdFlakeCheck : FlakeCommand auto checkOverlay = [&](std::string_view attrPath, Value & v, const PosIdx pos) { try { - Activity act(*logger, lvlInfo, actUnknown, fmt("checking overlay '%s'", attrPath)); + Activity act(*logger, Verbosity::Info, ActivityType::Unknown, fmt("checking overlay '%s'", attrPath)); state->forceValue(v, pos); if (!v.isLambda()) { throw Error("overlay is not a function, but %s instead", showType(v)); @@ -480,7 +482,8 @@ struct CmdFlakeCheck : FlakeCommand auto checkModule = [&](std::string_view attrPath, Value & v, const PosIdx pos) { try { - Activity act(*logger, lvlInfo, actUnknown, fmt("checking NixOS module '%s'", attrPath)); + Activity act( + *logger, Verbosity::Info, ActivityType::Unknown, fmt("checking NixOS module '%s'", attrPath)); state->forceValue(v, pos); } catch (Error & e) { e.addTrace(resolve(pos), HintFmt("while checking the NixOS module '%s'", attrPath)); @@ -492,7 +495,7 @@ struct CmdFlakeCheck : FlakeCommand checkHydraJobs = [&](std::string_view attrPath, Value & v, const PosIdx pos) { try { - Activity act(*logger, lvlInfo, actUnknown, fmt("checking Hydra job '%s'", attrPath)); + Activity act(*logger, Verbosity::Info, ActivityType::Unknown, fmt("checking Hydra job '%s'", attrPath)); state->forceAttrs(v, pos, ""); if (state->isDerivation(v)) @@ -502,7 +505,8 @@ struct CmdFlakeCheck : FlakeCommand state->forceAttrs(*attr.value, attr.pos, ""); auto attrPath2 = concatStrings(attrPath, ".", state->symbols[attr.name]); if (state->isDerivation(*attr.value)) { - Activity act(*logger, lvlInfo, actUnknown, fmt("checking Hydra job '%s'", attrPath2)); + Activity act( + *logger, Verbosity::Info, ActivityType::Unknown, fmt("checking Hydra job '%s'", attrPath2)); checkDerivation(attrPath2, *attr.value, attr.pos); } else checkHydraJobs(attrPath2, *attr.value, attr.pos); @@ -516,7 +520,11 @@ struct CmdFlakeCheck : FlakeCommand auto checkNixOSConfiguration = [&](const std::string & attrPath, Value & v, const PosIdx pos) { try { - Activity act(*logger, lvlInfo, actUnknown, fmt("checking NixOS configuration '%s'", attrPath)); + Activity act( + *logger, + Verbosity::Info, + ActivityType::Unknown, + fmt("checking NixOS configuration '%s'", attrPath)); Bindings & bindings = Bindings::emptyBindings; auto vToplevel = findAlongAttrPath(*state, "config.system.build.toplevel", bindings, v).first; state->forceValue(*vToplevel, pos); @@ -530,7 +538,7 @@ struct CmdFlakeCheck : FlakeCommand auto checkTemplate = [&](std::string_view attrPath, Value & v, const PosIdx pos) { try { - Activity act(*logger, lvlInfo, actUnknown, fmt("checking template '%s'", attrPath)); + Activity act(*logger, Verbosity::Info, ActivityType::Unknown, fmt("checking template '%s'", attrPath)); state->forceAttrs(v, pos, ""); @@ -563,7 +571,7 @@ struct CmdFlakeCheck : FlakeCommand auto checkBundler = [&](const std::string & attrPath, Value & v, const PosIdx pos) { try { - Activity act(*logger, lvlInfo, actUnknown, fmt("checking bundler '%s'", attrPath)); + Activity act(*logger, Verbosity::Info, ActivityType::Unknown, fmt("checking bundler '%s'", attrPath)); state->forceValue(v, pos); if (!v.isLambda()) throw Error("bundler must be a function"); @@ -575,13 +583,13 @@ struct CmdFlakeCheck : FlakeCommand }; { - Activity act(*logger, lvlInfo, actUnknown, "evaluating flake"); + Activity act(*logger, Verbosity::Info, ActivityType::Unknown, "evaluating flake"); auto vFlake = state->allocValue(); flake::callFlake(*state, flake, *vFlake); enumerateOutputs(*state, *vFlake, [&](std::string_view name, Value & vOutput, const PosIdx pos) { - Activity act(*logger, lvlInfo, actUnknown, fmt("checking flake output '%s'", name)); + Activity act(*logger, Verbosity::Info, ActivityType::Unknown, fmt("checking flake output '%s'", name)); try { evalSettings.enableImportFromDerivation.setDefault(name != "hydraJobs"); @@ -811,7 +819,8 @@ struct CmdFlakeCheck : FlakeCommand }); } - Activity act(*logger, lvlInfo, actUnknown, fmt("running %d flake checks", toBuild.size())); + Activity act( + *logger, Verbosity::Info, ActivityType::Unknown, fmt("running %d flake checks", toBuild.size())); auto results = store->buildPathsWithResults(toBuild); // Report build failures with attribute paths @@ -838,7 +847,7 @@ struct CmdFlakeCheck : FlakeCommand if (hasErrors) throw Error("some errors were encountered during the evaluation"); - logger->log(lvlInfo, ANSI_GREEN "all checks passed!" ANSI_NORMAL); + logger->log(Verbosity::Info, ANSI_GREEN "all checks passed!" ANSI_NORMAL); if (!omittedSystems.empty()) { // TODO: empty system is not visible; render all as nix strings? @@ -1238,7 +1247,11 @@ struct CmdFlakeShow : FlakeCommand, MixJSON auto attrPathS = state->symbols.resolve(attrPath); - Activity act(*logger, lvlInfo, actUnknown, fmt("evaluating '%s'", concatStringsSep(".", attrPathS))); + Activity act( + *logger, + Verbosity::Info, + ActivityType::Unknown, + fmt("evaluating '%s'", concatStringsSep(".", attrPathS))); try { auto recurse = [&]() { diff --git a/src/nix/main.cc b/src/nix/main.cc index 93c1dc42a38..69880f07ec6 100644 --- a/src/nix/main.cc +++ b/src/nix/main.cc @@ -427,9 +427,9 @@ void mainWrapped(int argc, char ** argv) // If on a terminal, progress will be displayed via progress bars etc. (thus verbosity=notice) if (nix::isTTY()) { - verbosity = lvlNotice; + verbosity = Verbosity::Notice; } else { - verbosity = lvlInfo; + verbosity = Verbosity::Info; } NixArgs args; diff --git a/src/nix/nix-build/nix-build.cc b/src/nix/nix-build/nix-build.cc index a21d1a56549..ee87fccce09 100644 --- a/src/nix/nix-build/nix-build.cc +++ b/src/nix/nix-build/nix-build.cc @@ -6,6 +6,7 @@ #include #include #include +#include #include @@ -509,7 +510,7 @@ static void main_nix_build(int argc, char ** argv) // To get around lambda capturing restrictions in the // standard. const auto & inputDrv = inputDrv0; - if (std::all_of(envExclude.cbegin(), envExclude.cend(), [&](const std::string & exclude) { + if (std::ranges::all_of(envExclude, [&](const std::string & exclude) { return !std::regex_search(store->printStorePath(inputDrv), std::regex(exclude)); })) { accumDerivedPath(makeConstantStorePathRef(inputDrv), inputNode); @@ -564,14 +565,14 @@ static void main_nix_build(int argc, char ** argv) int fileNr = 0; - for (auto & var : drv.env) - if (drvOptions.passAsFile.count(var.first)) { + for (auto & [varName, varValue] : drv.env) + if (drvOptions.passAsFile.count(varName)) { auto fn = ".attr-" + std::to_string(fileNr++); Path p = (tmpDir.path() / fn).string(); - writeFile(p, var.second); - env[var.first + "Path"] = p; + writeFile(p, varValue); + env[varName + "Path"] = p; } else - env[var.first] = var.second; + env[varName] = varValue; std::string structuredAttrsRC; @@ -652,8 +653,8 @@ static void main_nix_build(int argc, char ** argv) writeFile(rcfile, rc); Strings envStrs; - for (auto & i : env) - envStrs.push_back(i.first + "=" + i.second); + for (auto & [name, value] : env) + envStrs.push_back(name + "=" + value); auto args = interactive ? Strings{"bash", "--rcfile", rcfile} : Strings{"bash", rcfile}; diff --git a/src/nix/nix-copy-closure/nix-copy-closure.cc b/src/nix/nix-copy-closure/nix-copy-closure.cc index 87d0f65905b..a554d6f96dd 100644 --- a/src/nix/nix-copy-closure/nix-copy-closure.cc +++ b/src/nix/nix-copy-closure/nix-copy-closure.cc @@ -33,7 +33,7 @@ static int main_nix_copy_closure(int argc, char ** argv) else if (*arg == "--include-outputs") includeOutputs = true; else if (*arg == "--show-progress") - printMsg(lvlError, "Warning: '--show-progress' is not implemented"); + printMsg(Verbosity::Error, "Warning: '--show-progress' is not implemented"); else if (*arg == "--dry-run") dryRun = true; else if (*arg == "--use-substitutes" || *arg == "-s") diff --git a/src/nix/nix-env/nix-env.cc b/src/nix/nix-env/nix-env.cc index edfccffa610..3ece5eb64f1 100644 --- a/src/nix/nix-env/nix-env.cc +++ b/src/nix/nix-env/nix-env.cc @@ -945,7 +945,10 @@ queryJSON(Globals & globals, std::vector & elems, bool printOutPath } } } catch (AssertionError & e) { - printMsg(lvlTalkative, "skipping derivation named '%1%' which gives an assertion failure", i.queryName()); + printMsg( + Verbosity::Talkative, + "skipping derivation named '%1%' which gives an assertion failure", + i.queryName()); } catch (Error & e) { e.addTrace(nullptr, "while querying the derivation named '%1%'", i.queryName()); throw; @@ -1059,7 +1062,9 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs) paths.insert(i.queryOutPath()); } catch (AssertionError & e) { printMsg( - lvlTalkative, "skipping derivation named '%s' which gives an assertion failure", i.queryName()); + Verbosity::Talkative, + "skipping derivation named '%s' which gives an assertion failure", + i.queryName()); i.setFailed(); } validPaths = store.queryValidPaths(paths); @@ -1086,7 +1091,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs) if (i.hasFailed()) continue; - // Activity act(*logger, lvlDebug, "outputting query result '%1%'", i.attrPath); + // Activity act(*logger, Verbosity::Debug, "outputting query result '%1%'", i.attrPath); if (globals.prebuiltOnly && !validPaths.count(i.queryOutPath()) && !substitutablePaths.count(i.queryOutPath())) @@ -1273,7 +1278,10 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs) cout.flush(); } catch (AssertionError & e) { - printMsg(lvlTalkative, "skipping derivation named '%1%' which gives an assertion failure", i.queryName()); + printMsg( + Verbosity::Talkative, + "skipping derivation named '%1%' which gives an assertion failure", + i.queryName()); } catch (Error & e) { e.addTrace(nullptr, "while querying the derivation named '%1%'", i.queryName()); throw; diff --git a/src/nix/nix-env/user-env.cc b/src/nix/nix-env/user-env.cc index 5beed78f724..1c86f06426a 100644 --- a/src/nix/nix-env/user-env.cc +++ b/src/nix/nix-env/user-env.cc @@ -68,18 +68,19 @@ bool createUserEnv( // Copy each output meant for installation. auto outputsList = state.buildList(outputs.size()); - for (const auto & [m, j] : enumerate(outputs)) { - (outputsList[m] = state.allocValue())->mkString(j.first, state.mem); + for (const auto & [m, output] : enumerate(outputs)) { + auto & [outputName, outputPath] = output; + (outputsList[m] = state.allocValue())->mkString(outputName, state.mem); auto outputAttrs = state.buildBindings(2); - outputAttrs.alloc(state.s.outPath).mkString(state.store->printStorePath(*j.second), state.mem); - attrs.alloc(j.first).mkAttrs(outputAttrs); + outputAttrs.alloc(state.s.outPath).mkString(state.store->printStorePath(*outputPath), state.mem); + attrs.alloc(outputName).mkAttrs(outputAttrs); /* This is only necessary when installing store paths, e.g., `nix-env -i /nix/store/abcd...-foo'. */ - state.store->addTempRoot(*j.second); - state.store->ensurePath(*j.second); + state.store->addTempRoot(*outputPath); + state.store->ensurePath(*outputPath); - references.insert(*j.second); + references.insert(*outputPath); } attrs.alloc(state.s.outputs).mkList(outputsList); diff --git a/src/nix/nix-store/nix-store.cc b/src/nix/nix-store/nix-store.cc index 3798c7fa015..6caab182328 100644 --- a/src/nix/nix-store/nix-store.cc +++ b/src/nix/nix-store/nix-store.cc @@ -838,7 +838,7 @@ static void opVerifyPath(Strings opFlags, Strings opArgs) for (auto & i : opArgs) { auto path = store->followLinksToStorePath(i); - printMsg(lvlTalkative, "checking path '%s'...", store->printStorePath(path)); + printMsg(Verbosity::Talkative, "checking path '%s'...", store->printStorePath(path)); auto info = store->queryPathInfo(path); HashSink sink(info->narHash.algo); store->narFromPath(path, sink); @@ -908,7 +908,7 @@ static void opServe(Strings opFlags, Strings opArgs) auto getBuildSettings = [&]() { // FIXME: changing options here doesn't work if we're // building through the daemon. - verbosity = lvlError; + verbosity = Verbosity::Error; settings.keepLog = false; settings.useSubstitutes = false; diff --git a/src/nix/prefetch.cc b/src/nix/prefetch.cc index d494b098686..0f6b54b55a9 100644 --- a/src/nix/prefetch.cc +++ b/src/nix/prefetch.cc @@ -125,7 +125,7 @@ std::tuple prefetchFile( /* Optionally unpack the file. */ if (unpack) { - Activity act(*logger, lvlChatty, actUnknown, fmt("unpacking '%s'", url.to_string())); + Activity act(*logger, Verbosity::Chatty, ActivityType::Unknown, fmt("unpacking '%s'", url.to_string())); auto unpacked = (tmpDir.path() / "unpacked").string(); createDirs(unpacked); unpackTarfile(tmpFile.string(), unpacked); @@ -141,7 +141,8 @@ std::tuple prefetchFile( } } - Activity act(*logger, lvlChatty, actUnknown, fmt("adding '%s' to the store", url.to_string())); + Activity act( + *logger, Verbosity::Chatty, ActivityType::Unknown, fmt("adding '%s' to the store", url.to_string())); auto info = store->addToStoreSlow(name, makeFSSourceAccessor(tmpFile), method, hashAlgo, {}, expectedHash); storePath = info.path; diff --git a/src/nix/profile.cc b/src/nix/profile.cc index 5b0e033e03e..9f838e6a853 100644 --- a/src/nix/profile.cc +++ b/src/nix/profile.cc @@ -14,6 +14,7 @@ #include "nix/flake/url-name.hh" #include +#include #include #include @@ -43,7 +44,7 @@ struct ProfileElementSource } }; -const int defaultPriority = 5; +constexpr int defaultPriority = 5; struct ProfileElement { @@ -601,11 +602,8 @@ class MixProfileElementMatchers : virtual Args, virtual StoreCommand throw UsageError("No packages specified."); } - if (std::find_if( - _matchers.begin(), - _matchers.end(), - [](const ref & m) { return m.dynamic_pointer_cast(); }) - != _matchers.end() + if (std::ranges::any_of( + _matchers, [](const ref & m) { return m.dynamic_pointer_cast() != nullptr; }) && _matchers.size() > 1) { throw UsageError("--all cannot be used with package names or regular expressions."); } @@ -720,7 +718,11 @@ struct CmdProfileUpgrade : virtual SourceExprCommand, MixDefaultProfile, MixProf upgradedCount++; - Activity act(*logger, lvlChatty, actUnknown, fmt("checking '%s' for updates", element.source->attrPath)); + Activity act( + *logger, + Verbosity::Chatty, + ActivityType::Unknown, + fmt("checking '%s' for updates", element.source->attrPath)); auto installable = make_ref( this, diff --git a/src/nix/run.cc b/src/nix/run.cc index 324b736a6a5..a10a2adc054 100644 --- a/src/nix/run.cc +++ b/src/nix/run.cc @@ -38,8 +38,8 @@ namespace nix { Strings toEnvp(StringMap env) { Strings envStrs; - for (auto & i : env) { - envStrs.push_back(i.first + "=" + i.second); + for (auto & [name, value] : env) { + envStrs.push_back(name + "=" + value); } return envStrs; diff --git a/src/nix/search.cc b/src/nix/search.cc index 20bb4cd5dff..b526ca37bc1 100644 --- a/src/nix/search.cc +++ b/src/nix/search.cc @@ -96,7 +96,11 @@ struct CmdSearch : InstallableValueCommand, MixJSON visit = [&](eval_cache::AttrCursor & cursor, const std::vector & attrPath, bool initialRecurse) { auto attrPathS = state->symbols.resolve(attrPath); - Activity act(*logger, lvlInfo, actUnknown, fmt("evaluating '%s'", concatStringsSep(".", attrPathS))); + Activity act( + *logger, + Verbosity::Info, + ActivityType::Unknown, + fmt("evaluating '%s'", concatStringsSep(".", attrPathS))); try { auto recurse = [&]() { for (const auto & attr : cursor.getAttrs()) { diff --git a/src/nix/sigs.cc b/src/nix/sigs.cc index e82f0d284b9..63f896eb572 100644 --- a/src/nix/sigs.cc +++ b/src/nix/sigs.cc @@ -53,7 +53,7 @@ struct CmdCopySigs : StorePathsCommand // logger->setExpected(doneLabel, storePaths.size()); auto doPath = [&](const Path & storePathS) { - // Activity act(*logger, lvlInfo, "getting signatures for '%s'", storePath); + // Activity act(*logger, Verbosity::Info, "getting signatures for '%s'", storePath); checkInterrupt(); diff --git a/src/nix/unix/daemon.cc b/src/nix/unix/daemon.cc index 33ad8757a51..0fdd50b8c6a 100644 --- a/src/nix/unix/daemon.cc +++ b/src/nix/unix/daemon.cc @@ -174,7 +174,7 @@ static bool matchUser(std::string_view user, const struct group & gr) * * Otherwise: No. */ -static bool matchUser(const std::string & user, const std::string & group, const Strings & users) +static bool matchUser(std::string_view user, std::string_view group, const Strings & users) { if (find(users.begin(), users.end(), "*") != users.end()) return true; diff --git a/src/nix/upgrade-nix.cc b/src/nix/upgrade-nix.cc index f26613bf899..5ab88059abd 100644 --- a/src/nix/upgrade-nix.cc +++ b/src/nix/upgrade-nix.cc @@ -80,13 +80,20 @@ struct CmdUpgradeNix : MixDryRun, StoreCommand } { - Activity act(*logger, lvlInfo, actUnknown, fmt("downloading '%s'...", store->printStorePath(storePath))); + Activity act( + *logger, + Verbosity::Info, + ActivityType::Unknown, + fmt("downloading '%s'...", store->printStorePath(storePath))); store->ensurePath(storePath); } { Activity act( - *logger, lvlInfo, actUnknown, fmt("verifying that '%s' works...", store->printStorePath(storePath))); + *logger, + Verbosity::Info, + ActivityType::Unknown, + fmt("verifying that '%s' works...", store->printStorePath(storePath))); auto program = store->printStorePath(storePath) + "/bin/nix-env"; auto s = runProgram(program, false, {"--version"}); if (s.find("Nix") == std::string::npos) @@ -98,8 +105,8 @@ struct CmdUpgradeNix : MixDryRun, StoreCommand { Activity act( *logger, - lvlInfo, - actUnknown, + Verbosity::Info, + ActivityType::Unknown, fmt("installing '%s' into profile %s...", store->printStorePath(storePath), profileDir)); // FIXME: don't call an external process. @@ -153,7 +160,7 @@ struct CmdUpgradeNix : MixDryRun, StoreCommand /* Return the store path of the latest stable Nix. */ StorePath getLatestNix(ref store) { - Activity act(*logger, lvlInfo, actUnknown, "querying latest Nix version"); + Activity act(*logger, Verbosity::Info, ActivityType::Unknown, "querying latest Nix version"); // FIXME: use nixos.org? auto req = FileTransferRequest(parseURL(settings.upgradeNixStorePathUrl.get())); diff --git a/src/nix/verify.cc b/src/nix/verify.cc index 309d19a1d4e..253abd15c05 100644 --- a/src/nix/verify.cc +++ b/src/nix/verify.cc @@ -69,7 +69,7 @@ struct CmdVerify : StorePathsCommand auto publicKeys = getDefaultPublicKeys(); - Activity act(*logger, actVerifyPaths); + Activity act(*logger, ActivityType::VerifyPaths); std::atomic done{0}; std::atomic untrusted{0}; @@ -93,7 +93,11 @@ struct CmdVerify : StorePathsCommand // Note: info->path can be different from storePath // for binary cache stores when using --all (since we // can't enumerate names efficiently). - Activity act2(*logger, lvlInfo, actUnknown, fmt("checking '%s'", store->printStorePath(info->path))); + Activity act2( + *logger, + Verbosity::Info, + ActivityType::Unknown, + fmt("checking '%s'", store->printStorePath(info->path))); if (!noContents) { @@ -105,7 +109,7 @@ struct CmdVerify : StorePathsCommand if (hash.hash != info->narHash) { corrupted++; - act2.result(resCorruptedPath, store->printStorePath(info->path)); + act2.result(ResultType::CorruptedPath, store->printStorePath(info->path)); printError( "path '%s' was modified! expected hash '%s', got '%s'", store->printStorePath(info->path), @@ -161,7 +165,7 @@ struct CmdVerify : StorePathsCommand if (!good) { untrusted++; - act2.result(resUntrustedPath, store->printStorePath(info->path)); + act2.result(ResultType::UntrustedPath, store->printStorePath(info->path)); printError("path '%s' is untrusted", store->printStorePath(info->path)); } } diff --git a/src/nix/why-depends.cc b/src/nix/why-depends.cc index 29da9e953e8..3b01289a327 100644 --- a/src/nix/why-depends.cc +++ b/src/nix/why-depends.cc @@ -13,7 +13,7 @@ static std::string hilite(const std::string & s, size_t pos, size_t len, const s return std::string(s, 0, pos) + colour + std::string(s, pos, len) + ANSI_NORMAL + std::string(s, pos + len); } -static std::string filterPrintable(const std::string & s) +static std::string filterPrintable(std::string_view s) { std::string res; for (char c : s) @@ -133,9 +133,9 @@ struct CmdWhyDepends : SourceExprCommand, MixOperateOnOptions .dist = path == dependencyPath ? 0 : inf}); // Transpose the graph. - for (auto & node : graph) - for (auto & ref : node.second.refs) - graph.find(ref)->second.rrefs.insert(node.first); + for (auto & [path, node] : graph) + for (auto & ref : node.refs) + graph.find(ref)->second.rrefs.insert(path); /* Run Dijkstra's shortest path algorithm to get the distance of every path in the closure to 'dependency'. */