From df552ff53e68dff8ca360adbdbea214ece1d08ee Mon Sep 17 00:00:00 2001 From: Eelco Dolstra Date: Fri, 25 Feb 2022 16:00:00 +0100 Subject: [PATCH] Remove std::string alias (for real this time) Also use std::string_view in a few more places. --- perl/lib/Nix/Store.xs | 2 +- src/build-remote/build-remote.cc | 10 +-- src/libexpr/attr-path.cc | 6 +- src/libexpr/attr-path.hh | 7 +- src/libexpr/attr-set.hh | 2 +- src/libexpr/common-eval-args.cc | 8 +- src/libexpr/common-eval-args.hh | 2 +- src/libexpr/eval-cache.cc | 2 +- src/libexpr/eval.cc | 66 +++++++-------- src/libexpr/eval.hh | 20 ++--- src/libexpr/flake/flake.cc | 4 +- src/libexpr/get-drvs.cc | 40 ++++----- src/libexpr/get-drvs.hh | 46 +++++----- src/libexpr/nixexpr.cc | 14 ++-- src/libexpr/nixexpr.hh | 19 +++-- src/libexpr/parser.y | 30 +++---- src/libexpr/primops.cc | 46 +++++----- src/libexpr/primops/context.cc | 10 +-- src/libexpr/primops/fetchMercurial.cc | 2 +- src/libexpr/primops/fetchTree.cc | 4 +- src/libexpr/primops/fromTOML.cc | 2 +- src/libexpr/value-to-xml.cc | 2 +- src/libfetchers/mercurial.cc | 4 +- src/libmain/common-args.cc | 2 +- src/libmain/common-args.hh | 4 +- src/libmain/shared.cc | 16 ++-- src/libmain/shared.hh | 14 ++-- src/libstore/binary-cache-store.cc | 17 +++- src/libstore/binary-cache-store.hh | 18 ++-- src/libstore/build/derivation-goal.cc | 14 ++-- src/libstore/build/derivation-goal.hh | 4 +- .../build/drv-output-substitution-goal.cc | 2 +- .../build/drv-output-substitution-goal.hh | 2 +- src/libstore/build/goal.cc | 4 +- src/libstore/build/goal.hh | 8 +- src/libstore/build/local-derivation-goal.cc | 64 ++++++++------ src/libstore/build/local-derivation-goal.hh | 2 +- src/libstore/build/substitution-goal.cc | 2 +- src/libstore/build/substitution-goal.hh | 4 +- src/libstore/build/worker.cc | 2 +- src/libstore/builtins/buildenv.cc | 4 +- src/libstore/builtins/fetchurl.cc | 2 +- src/libstore/builtins/unpack-channel.cc | 2 +- src/libstore/daemon.cc | 8 +- src/libstore/derivations.cc | 32 +++---- src/libstore/derivations.hh | 12 ++- src/libstore/derived-path.cc | 4 +- src/libstore/dummy-store.cc | 9 +- src/libstore/filetransfer.cc | 26 +++--- src/libstore/filetransfer.hh | 8 +- src/libstore/gc.cc | 23 +++-- src/libstore/globals.cc | 4 +- src/libstore/globals.hh | 2 +- src/libstore/legacy-ssh-store.cc | 22 +++-- src/libstore/local-fs-store.cc | 2 +- src/libstore/local-fs-store.hh | 2 +- src/libstore/local-store.cc | 29 ++++--- src/libstore/local-store.hh | 13 ++- src/libstore/lock.hh | 4 +- src/libstore/machines.cc | 21 ++--- src/libstore/nar-accessor.cc | 2 +- src/libstore/nar-info.cc | 2 +- src/libstore/optimise-store.cc | 2 +- src/libstore/path-with-outputs.cc | 4 +- src/libstore/path.hh | 2 +- src/libstore/pathlocks.cc | 4 +- src/libstore/pathlocks.hh | 4 +- src/libstore/profiles.cc | 16 ++-- src/libstore/profiles.hh | 4 +- src/libstore/references.cc | 4 +- src/libstore/remote-store.cc | 11 ++- src/libstore/remote-store.hh | 7 +- src/libstore/s3-binary-cache-store.cc | 11 ++- src/libstore/sqlite.cc | 2 +- src/libstore/ssh.cc | 2 +- src/libstore/store-api.cc | 32 ++++--- src/libstore/store-api.hh | 26 ++++-- src/libutil/archive.cc | 28 +++---- src/libutil/archive.hh | 6 +- src/libutil/args.cc | 12 +-- src/libutil/args.hh | 2 +- src/libutil/config.cc | 14 ++-- src/libutil/error.cc | 12 +-- src/libutil/error.hh | 26 +++--- src/libutil/fmt.hh | 7 +- src/libutil/hash.cc | 19 +++-- src/libutil/hash.hh | 6 +- src/libutil/logging.cc | 2 +- src/libutil/logging.hh | 2 +- src/libutil/serialise.cc | 4 +- src/libutil/serialise.hh | 4 +- src/libutil/tests/url.cc | 18 ++-- src/libutil/types.hh | 1 + src/libutil/util.cc | 84 +++++++++---------- src/libutil/util.hh | 44 +++++----- src/nix-build/nix-build.cc | 16 ++-- src/nix-channel/nix-channel.cc | 14 ++-- .../nix-collect-garbage.cc | 2 +- src/nix-env/nix-env.cc | 82 +++++++++--------- src/nix-env/user-env.cc | 2 +- src/nix-env/user-env.hh | 2 +- src/nix-instantiate/nix-instantiate.cc | 2 +- src/nix-store/dotgraph.cc | 26 +++--- src/nix-store/graphml.cc | 8 +- src/nix-store/nix-store.cc | 16 ++-- src/nix/daemon.cc | 16 ++-- src/nix/hash.cc | 2 +- src/nix/prefetch.cc | 14 ++-- src/nix/repl.cc | 66 +++++++-------- src/nix/why-depends.cc | 4 +- 110 files changed, 773 insertions(+), 681 deletions(-) diff --git a/perl/lib/Nix/Store.xs b/perl/lib/Nix/Store.xs index edbf12f7c..54ad1680c 100644 --- a/perl/lib/Nix/Store.xs +++ b/perl/lib/Nix/Store.xs @@ -240,7 +240,7 @@ SV * convertHash(char * algo, char * s, int toBase32) PPCODE: try { auto h = Hash::parseAny(s, parseHashType(algo)); - string s = h.to_string(toBase32 ? Base32 : Base16, false); + auto s = h.to_string(toBase32 ? Base32 : Base16, false); XPUSHs(sv_2mortal(newSVpv(s.c_str(), 0))); } catch (Error & e) { croak("%s", e.what()); diff --git a/src/build-remote/build-remote.cc b/src/build-remote/build-remote.cc index 4d7b602d8..9d2eacb54 100644 --- a/src/build-remote/build-remote.cc +++ b/src/build-remote/build-remote.cc @@ -32,7 +32,7 @@ std::string escapeUri(std::string uri) return uri; } -static string currentLoad; +static std::string currentLoad; static AutoCloseFD openSlotLock(const Machine & m, uint64_t slot) { @@ -97,7 +97,7 @@ static int main_build_remote(int argc, char * * argv) } std::optional drvPath; - string storeUri; + std::string storeUri; while (true) { @@ -183,7 +183,7 @@ static int main_build_remote(int argc, char * * argv) else { // build the hint template. - string errorText = + std::string errorText = "Failed to find a machine for remote build!\n" "derivation: %s\nrequired (system, features): (%s, %s)"; errorText += "\n%s available machines:"; @@ -193,7 +193,7 @@ static int main_build_remote(int argc, char * * argv) errorText += "\n(%s, %s, %s, %s)"; // add the template values. - string drvstr; + std::string drvstr; if (drvPath.has_value()) drvstr = drvPath->to_string(); else @@ -208,7 +208,7 @@ static int main_build_remote(int argc, char * * argv) for (auto & m : machines) error - % concatStringsSep>(", ", m.systemTypes) + % concatStringsSep>(", ", m.systemTypes) % m.maxJobs % concatStringsSep(", ", m.supportedFeatures) % concatStringsSep(", ", m.mandatoryFeatures); diff --git a/src/libexpr/attr-path.cc b/src/libexpr/attr-path.cc index bf0c1dabc..eb0e706c7 100644 --- a/src/libexpr/attr-path.cc +++ b/src/libexpr/attr-path.cc @@ -9,7 +9,7 @@ namespace nix { static Strings parseAttrPath(std::string_view s) { Strings res; - string cur; + std::string cur; auto i = s.begin(); while (i != s.end()) { if (*i == '.') { @@ -41,7 +41,7 @@ std::vector parseAttrPath(EvalState & state, std::string_view s) } -std::pair findAlongAttrPath(EvalState & state, const string & attrPath, +std::pair findAlongAttrPath(EvalState & state, const std::string & attrPath, Bindings & autoArgs, Value & vIn) { Strings tokens = parseAttrPath(attrPath); @@ -121,7 +121,7 @@ Pos findPackageFilename(EvalState & state, Value & v, std::string what) std::string filename(pos, 0, colon); unsigned int lineno; try { - lineno = std::stoi(std::string(pos, colon + 1, string::npos)); + lineno = std::stoi(std::string(pos, colon + 1, std::string::npos)); } catch (std::invalid_argument & e) { throw ParseError("cannot parse line number '%s'", pos); } diff --git a/src/libexpr/attr-path.hh b/src/libexpr/attr-path.hh index 2ee3ea089..ff1135a06 100644 --- a/src/libexpr/attr-path.hh +++ b/src/libexpr/attr-path.hh @@ -10,8 +10,11 @@ namespace nix { MakeError(AttrPathNotFound, Error); MakeError(NoPositionInfo, Error); -std::pair findAlongAttrPath(EvalState & state, const string & attrPath, - Bindings & autoArgs, Value & vIn); +std::pair findAlongAttrPath( + EvalState & state, + const std::string & attrPath, + Bindings & autoArgs, + Value & vIn); /* Heuristic to find the filename and lineno or a nix value. */ Pos findPackageFilename(EvalState & state, Value & v, std::string what); diff --git a/src/libexpr/attr-set.hh b/src/libexpr/attr-set.hh index 3e4899efc..cad9743ea 100644 --- a/src/libexpr/attr-set.hh +++ b/src/libexpr/attr-set.hh @@ -105,7 +105,7 @@ public: for (size_t n = 0; n < size_; n++) res.emplace_back(&attrs[n]); std::sort(res.begin(), res.end(), [](const Attr * a, const Attr * b) { - return (const string &) a->name < (const string &) b->name; + return (const std::string &) a->name < (const std::string &) b->name; }); return res; } diff --git a/src/libexpr/common-eval-args.cc b/src/libexpr/common-eval-args.cc index fffca4ac5..e50ff244c 100644 --- a/src/libexpr/common-eval-args.cc +++ b/src/libexpr/common-eval-args.cc @@ -77,7 +77,7 @@ Bindings * MixEvalArgs::getAutoArgs(EvalState & state) for (auto & i : autoArgs) { auto v = state.allocValue(); if (i.second[0] == 'E') - state.mkThunk_(*v, state.parseExprFromString(string(i.second, 1), absPath("."))); + state.mkThunk_(*v, state.parseExprFromString(i.second.substr(1), absPath("."))); else v->mkString(((std::string_view) i.second).substr(1)); res.insert(state.symbols.create(i.first), v); @@ -85,17 +85,17 @@ Bindings * MixEvalArgs::getAutoArgs(EvalState & state) return res.finish(); } -Path lookupFileArg(EvalState & state, string s) +Path lookupFileArg(EvalState & state, std::string_view s) { if (isUri(s)) { return state.store->toRealPath( fetchers::downloadTarball( state.store, resolveUri(s), "source", false).first.storePath); } else if (s.size() > 2 && s.at(0) == '<' && s.at(s.size() - 1) == '>') { - Path p = s.substr(1, s.size() - 2); + Path p(s.substr(1, s.size() - 2)); return state.findFile(p); } else - return absPath(s); + return absPath(std::string(s)); } } diff --git a/src/libexpr/common-eval-args.hh b/src/libexpr/common-eval-args.hh index 0e113fff1..03fa226aa 100644 --- a/src/libexpr/common-eval-args.hh +++ b/src/libexpr/common-eval-args.hh @@ -22,6 +22,6 @@ private: std::map autoArgs; }; -Path lookupFileArg(EvalState & state, string s); +Path lookupFileArg(EvalState & state, std::string_view s); } diff --git a/src/libexpr/eval-cache.cc b/src/libexpr/eval-cache.cc index d6b9ea29b..00d0749f9 100644 --- a/src/libexpr/eval-cache.cc +++ b/src/libexpr/eval-cache.cc @@ -596,7 +596,7 @@ std::vector AttrCursor::getAttrs() for (auto & attr : *getValue().attrs) attrs.push_back(attr.name); std::sort(attrs.begin(), attrs.end(), [](const Symbol & a, const Symbol & b) { - return (const string &) a < (const string &) b; + return (const std::string &) a < (const std::string &) b; }); if (root->db) diff --git a/src/libexpr/eval.cc b/src/libexpr/eval.cc index 2d4eb57fc..60f0bf08c 100644 --- a/src/libexpr/eval.cc +++ b/src/libexpr/eval.cc @@ -174,7 +174,7 @@ std::ostream & operator << (std::ostream & str, const Value & v) } -const Value *getPrimOp(const Value &v) { +const Value * getPrimOp(const Value &v) { const Value * primOp = &v; while (primOp->isPrimOpApp()) { primOp = primOp->primOpApp.left; @@ -183,7 +183,7 @@ const Value *getPrimOp(const Value &v) { return primOp; } -string showType(ValueType type) +std::string_view showType(ValueType type) { switch (type) { case nInt: return "an integer"; @@ -202,20 +202,20 @@ string showType(ValueType type) } -string showType(const Value & v) +std::string showType(const Value & v) { switch (v.internalType) { case tString: return v.string.context ? "a string with context" : "a string"; case tPrimOp: - return fmt("the built-in function '%s'", string(v.primOp->name)); + return fmt("the built-in function '%s'", std::string(v.primOp->name)); case tPrimOpApp: - return fmt("the partially applied built-in function '%s'", string(getPrimOp(v)->primOp->name)); + return fmt("the partially applied built-in function '%s'", std::string(getPrimOp(v)->primOp->name)); case tExternal: return v.external->showType(); case tThunk: return "a thunk"; case tApp: return "a function application"; case tBlackhole: return "a black hole"; default: - return showType(v.type()); + return std::string(showType(v.type())); } } @@ -356,7 +356,7 @@ void initGC() /* Very hacky way to parse $NIX_PATH, which is colon-separated, but can contain URLs (e.g. "nixpkgs=https://bla...:foo=https://"). */ -static Strings parseNixPath(const string & s) +static Strings parseNixPath(const std::string & s) { Strings res; @@ -606,7 +606,7 @@ Path EvalState::toRealPath(const Path & path, const PathSet & context) } -Value * EvalState::addConstant(const string & name, Value & v) +Value * EvalState::addConstant(const std::string & name, Value & v) { Value * v2 = allocValue(); *v2 = v; @@ -615,19 +615,19 @@ Value * EvalState::addConstant(const string & name, Value & v) } -void EvalState::addConstant(const string & name, Value * v) +void EvalState::addConstant(const std::string & name, Value * v) { staticBaseEnv.vars.emplace_back(symbols.create(name), baseEnvDispl); baseEnv.values[baseEnvDispl++] = v; - string name2 = string(name, 0, 2) == "__" ? string(name, 2) : name; + auto name2 = name.substr(0, 2) == "__" ? name.substr(2) : name; baseEnv.values[0]->attrs->push_back(Attr(symbols.create(name2), v)); } -Value * EvalState::addPrimOp(const string & name, +Value * EvalState::addPrimOp(const std::string & name, size_t arity, PrimOpFun primOp) { - auto name2 = string(name, 0, 2) == "__" ? string(name, 2) : name; + auto name2 = name.substr(0, 2) == "__" ? name.substr(2) : name; Symbol sym = symbols.create(name2); /* Hack to make constants lazy: turn them into a application of @@ -675,7 +675,7 @@ Value * EvalState::addPrimOp(PrimOp && primOp) } -Value & EvalState::getBuiltin(const string & name) +Value & EvalState::getBuiltin(const std::string & name) { return *baseEnv.values[0]->attrs->find(symbols.create(name))->value; } @@ -703,12 +703,12 @@ std::optional EvalState::getDoc(Value & v) evaluator. So here are some helper functions for throwing exceptions. */ -LocalNoInlineNoReturn(void throwEvalError(const char * s, const string & s2)) +LocalNoInlineNoReturn(void throwEvalError(const char * s, const std::string & s2)) { throw EvalError(s, s2); } -LocalNoInlineNoReturn(void throwEvalError(const Pos & pos, const char * s, const string & s2)) +LocalNoInlineNoReturn(void throwEvalError(const Pos & pos, const char * s, const std::string & s2)) { throw EvalError({ .msg = hintfmt(s, s2), @@ -716,12 +716,12 @@ LocalNoInlineNoReturn(void throwEvalError(const Pos & pos, const char * s, const }); } -LocalNoInlineNoReturn(void throwEvalError(const char * s, const string & s2, const string & s3)) +LocalNoInlineNoReturn(void throwEvalError(const char * s, const std::string & s2, const std::string & s3)) { throw EvalError(s, s2, s3); } -LocalNoInlineNoReturn(void throwEvalError(const Pos & pos, const char * s, const string & s2, const string & s3)) +LocalNoInlineNoReturn(void throwEvalError(const Pos & pos, const char * s, const std::string & s2, const std::string & s3)) { throw EvalError({ .msg = hintfmt(s, s2, s3), @@ -759,7 +759,7 @@ LocalNoInlineNoReturn(void throwTypeError(const char * s, const Value & v)) throw TypeError(s, showType(v)); } -LocalNoInlineNoReturn(void throwAssertionError(const Pos & pos, const char * s, const string & s1)) +LocalNoInlineNoReturn(void throwAssertionError(const Pos & pos, const char * s, const std::string & s1)) { throw AssertionError({ .msg = hintfmt(s, s1), @@ -767,7 +767,7 @@ LocalNoInlineNoReturn(void throwAssertionError(const Pos & pos, const char * s, }); } -LocalNoInlineNoReturn(void throwUndefinedVarError(const Pos & pos, const char * s, const string & s1)) +LocalNoInlineNoReturn(void throwUndefinedVarError(const Pos & pos, const char * s, const std::string & s1)) { throw UndefinedVarError({ .msg = hintfmt(s, s1), @@ -775,7 +775,7 @@ LocalNoInlineNoReturn(void throwUndefinedVarError(const Pos & pos, const char * }); } -LocalNoInlineNoReturn(void throwMissingArgumentError(const Pos & pos, const char * s, const string & s1)) +LocalNoInlineNoReturn(void throwMissingArgumentError(const Pos & pos, const char * s, const std::string & s1)) { throw MissingArgumentError({ .msg = hintfmt(s, s1), @@ -783,12 +783,12 @@ LocalNoInlineNoReturn(void throwMissingArgumentError(const Pos & pos, const char }); } -LocalNoInline(void addErrorTrace(Error & e, const char * s, const string & s2)) +LocalNoInline(void addErrorTrace(Error & e, const char * s, const std::string & s2)) { e.addTrace(std::nullopt, s, s2); } -LocalNoInline(void addErrorTrace(Error & e, const Pos & pos, const char * s, const string & s2)) +LocalNoInline(void addErrorTrace(Error & e, const Pos & pos, const char * s, const std::string & s2)) { e.addTrace(pos, s, s2); } @@ -1221,7 +1221,7 @@ void ExprVar::eval(EvalState & state, Env & env, Value & v) } -static string showAttrPath(EvalState & state, Env & env, const AttrPath & attrPath) +static std::string showAttrPath(EvalState & state, Env & env, const AttrPath & attrPath) { std::ostringstream out; bool first = true; @@ -1395,7 +1395,7 @@ void EvalState::callFunction(Value & fun, size_t nrArgs, Value * * args, Value & if (loggerSettings.showTrace.get()) { addErrorTrace(e, lambda.pos, "while evaluating %s", (lambda.name.set() - ? "'" + (string) lambda.name + "'" + ? "'" + (const std::string &) lambda.name + "'" : "anonymous lambda")); addErrorTrace(e, pos, "from call site%s", ""); } @@ -1883,7 +1883,7 @@ std::string_view EvalState::forceString(Value & v, const Pos & pos) /* Decode a context string ‘!!’ into a pair . */ -std::pair decodeContext(std::string_view s) +std::pair decodeContext(std::string_view s) { if (s.at(0) == '!') { size_t index = s.find("!", 1); @@ -1946,7 +1946,7 @@ bool EvalState::isDerivation(Value & v) } -std::optional EvalState::tryAttrsToString(const Pos & pos, Value & v, +std::optional EvalState::tryAttrsToString(const Pos & pos, Value & v, PathSet & context, bool coerceMore, bool copyToStore) { auto i = v.attrs->find(sToString); @@ -2001,7 +2001,7 @@ BackedStringView EvalState::coerceToString(const Pos & pos, Value & v, PathSet & if (v.type() == nNull) return ""; if (v.isList()) { - string result; + std::string result; for (auto [n, v2] : enumerate(v.listItems())) { result += *coerceToString(pos, *v2, context, coerceMore, copyToStore); if (n < v.listSize() - 1 @@ -2017,7 +2017,7 @@ BackedStringView EvalState::coerceToString(const Pos & pos, Value & v, PathSet & } -string EvalState::copyPathToStore(PathSet & context, const Path & path) +std::string EvalState::copyPathToStore(PathSet & context, const Path & path) { if (nix::isDerivation(path)) throwEvalError("file names are not allowed to end in '%1%'", drvExtension); @@ -2043,7 +2043,7 @@ string EvalState::copyPathToStore(PathSet & context, const Path & path) Path EvalState::coerceToPath(const Pos & pos, Value & v, PathSet & context) { - string path = coerceToString(pos, v, context, false, false).toOwned(); + auto path = coerceToString(pos, v, context, false, false).toOwned(); if (path == "" || path[0] != '/') throwEvalError(pos, "string '%1%' doesn't represent an absolute path", path); return path; @@ -2213,11 +2213,11 @@ void EvalState::printStats() for (auto & i : functionCalls) { auto obj = list.object(); if (i.first->name.set()) - obj.attr("name", (const string &) i.first->name); + obj.attr("name", (const std::string &) i.first->name); else obj.attr("name", nullptr); if (i.first->pos) { - obj.attr("file", (const string &) i.first->pos.file); + obj.attr("file", (const std::string &) i.first->pos.file); obj.attr("line", i.first->pos.line); obj.attr("column", i.first->pos.column); } @@ -2229,7 +2229,7 @@ void EvalState::printStats() for (auto & i : attrSelects) { auto obj = list.object(); if (i.first) { - obj.attr("file", (const string &) i.first.file); + obj.attr("file", (const std::string &) i.first.file); obj.attr("line", i.first.line); obj.attr("column", i.first.column); } @@ -2246,7 +2246,7 @@ void EvalState::printStats() } -string ExternalValueBase::coerceToString(const Pos & pos, PathSet & context, bool copyMore, bool copyToStore) const +std::string ExternalValueBase::coerceToString(const Pos & pos, PathSet & context, bool copyMore, bool copyToStore) const { throw TypeError({ .msg = hintfmt("cannot coerce %1% to a string", showType()), diff --git a/src/libexpr/eval.hh b/src/libexpr/eval.hh index ce5a16e11..1f0e97b2e 100644 --- a/src/libexpr/eval.hh +++ b/src/libexpr/eval.hh @@ -150,7 +150,7 @@ public: const Pos & pos ); - void addToSearchPath(const string & s); + void addToSearchPath(const std::string & s); SearchPath getSearchPath() { return searchPath; } @@ -251,7 +251,7 @@ public: set with attribute `type = "derivation"'). */ bool isDerivation(Value & v); - std::optional tryAttrsToString(const Pos & pos, Value & v, + std::optional tryAttrsToString(const Pos & pos, Value & v, PathSet & context, bool coerceMore = false, bool copyToStore = true); /* String coercion. Converts strings, paths and derivations to a @@ -262,7 +262,7 @@ public: bool coerceMore = false, bool copyToStore = true, bool canonicalizePath = true); - string copyPathToStore(PathSet & context, const Path & path); + std::string copyPathToStore(PathSet & context, const Path & path); /* Path coercion. Converts strings, paths and derivations to a path. The result is guaranteed to be a canonicalised, absolute @@ -284,18 +284,18 @@ private: void createBaseEnv(); - Value * addConstant(const string & name, Value & v); + Value * addConstant(const std::string & name, Value & v); - void addConstant(const string & name, Value * v); + void addConstant(const std::string & name, Value * v); - Value * addPrimOp(const string & name, + Value * addPrimOp(const std::string & name, size_t arity, PrimOpFun primOp); Value * addPrimOp(PrimOp && primOp); public: - Value & getBuiltin(const string & name); + Value & getBuiltin(const std::string & name); struct Doc { @@ -414,12 +414,12 @@ private: /* Return a string representing the type of the value `v'. */ -string showType(ValueType type); -string showType(const Value & v); +std::string_view showType(ValueType type); +std::string showType(const Value & v); /* Decode a context string ‘!!’ into a pair . */ -std::pair decodeContext(std::string_view s); +std::pair decodeContext(std::string_view s); /* If `path' refers to a directory, then append "/default.nix". */ Path resolveExprPath(Path path); diff --git a/src/libexpr/flake/flake.cc b/src/libexpr/flake/flake.cc index 6e3fa41f7..ad0881641 100644 --- a/src/libexpr/flake/flake.cc +++ b/src/libexpr/flake/flake.cc @@ -254,7 +254,7 @@ static Flake getFlake( for (auto & setting : *nixConfig->value->attrs) { forceTrivialValue(state, *setting.value, *setting.pos); if (setting.value->type() == nString) - flake.config.settings.insert({setting.name, string(state.forceStringNoCtx(*setting.value, *setting.pos))}); + flake.config.settings.insert({setting.name, std::string(state.forceStringNoCtx(*setting.value, *setting.pos))}); else if (setting.value->type() == nPath) { PathSet emptyContext = {}; flake.config.settings.emplace( @@ -707,7 +707,7 @@ static void prim_getFlake(EvalState & state, const Pos & pos, Value * * args, Va { state.requireExperimentalFeatureOnEvaluation(Xp::Flakes, "builtins.getFlake", pos); - string flakeRefS(state.forceStringNoCtx(*args[0], pos)); + std::string flakeRefS(state.forceStringNoCtx(*args[0], pos)); auto flakeRef = parseFlakeRef(flakeRefS, {}, true); if (evalSettings.pureEval && !flakeRef.input.isLocked()) throw Error("cannot call 'getFlake' on unlocked flake reference '%s', at %s (use --impure to override)", flakeRefS, pos); diff --git a/src/libexpr/get-drvs.cc b/src/libexpr/get-drvs.cc index 167fb5fa9..8393e4225 100644 --- a/src/libexpr/get-drvs.cc +++ b/src/libexpr/get-drvs.cc @@ -11,8 +11,8 @@ namespace nix { -DrvInfo::DrvInfo(EvalState & state, const string & attrPath, Bindings * attrs) - : state(&state), attrs(attrs), attrPath(attrPath) +DrvInfo::DrvInfo(EvalState & state, std::string attrPath, Bindings * attrs) + : state(&state), attrs(attrs), attrPath(std::move(attrPath)) { } @@ -47,7 +47,7 @@ DrvInfo::DrvInfo(EvalState & state, ref store, const std::string & drvPat } -string DrvInfo::queryName() const +std::string DrvInfo::queryName() const { if (name == "" && attrs) { auto i = attrs->find(state->sName); @@ -58,7 +58,7 @@ string DrvInfo::queryName() const } -string DrvInfo::querySystem() const +std::string DrvInfo::querySystem() const { if (system == "" && attrs) { auto i = attrs->find(state->sSystem); @@ -68,7 +68,7 @@ string DrvInfo::querySystem() const } -string DrvInfo::queryDrvPath() const +std::string DrvInfo::queryDrvPath() const { if (drvPath == "" && attrs) { Bindings::iterator i = attrs->find(state->sDrvPath); @@ -79,7 +79,7 @@ string DrvInfo::queryDrvPath() const } -string DrvInfo::queryOutPath() const +std::string DrvInfo::queryOutPath() const { if (!outPath && attrs) { Bindings::iterator i = attrs->find(state->sOutPath); @@ -104,7 +104,7 @@ DrvInfo::Outputs DrvInfo::queryOutputs(bool onlyOutputsToInstall) /* For each output... */ for (auto elem : i->value->listItems()) { /* Evaluate the corresponding set. */ - string name(state->forceStringNoCtx(*elem, *i->pos)); + std::string name(state->forceStringNoCtx(*elem, *i->pos)); Bindings::iterator out = attrs->find(state->symbols.create(name)); if (out == attrs->end()) continue; // FIXME: throw error? state->forceAttrs(*out->value, *i->pos); @@ -138,7 +138,7 @@ DrvInfo::Outputs DrvInfo::queryOutputs(bool onlyOutputsToInstall) } -string DrvInfo::queryOutputName() const +std::string DrvInfo::queryOutputName() const { if (outputName == "" && attrs) { Bindings::iterator i = attrs->find(state->sOutputName); @@ -190,7 +190,7 @@ bool DrvInfo::checkMeta(Value & v) } -Value * DrvInfo::queryMeta(const string & name) +Value * DrvInfo::queryMeta(const std::string & name) { if (!getMeta()) return 0; Bindings::iterator a = meta->find(state->symbols.create(name)); @@ -199,7 +199,7 @@ Value * DrvInfo::queryMeta(const string & name) } -string DrvInfo::queryMetaString(const string & name) +std::string DrvInfo::queryMetaString(const std::string & name) { Value * v = queryMeta(name); if (!v || v->type() != nString) return ""; @@ -207,7 +207,7 @@ string DrvInfo::queryMetaString(const string & name) } -NixInt DrvInfo::queryMetaInt(const string & name, NixInt def) +NixInt DrvInfo::queryMetaInt(const std::string & name, NixInt def) { Value * v = queryMeta(name); if (!v) return def; @@ -221,7 +221,7 @@ NixInt DrvInfo::queryMetaInt(const string & name, NixInt def) return def; } -NixFloat DrvInfo::queryMetaFloat(const string & name, NixFloat def) +NixFloat DrvInfo::queryMetaFloat(const std::string & name, NixFloat def) { Value * v = queryMeta(name); if (!v) return def; @@ -236,7 +236,7 @@ NixFloat DrvInfo::queryMetaFloat(const string & name, NixFloat def) } -bool DrvInfo::queryMetaBool(const string & name, bool def) +bool DrvInfo::queryMetaBool(const std::string & name, bool def) { Value * v = queryMeta(name); if (!v) return def; @@ -251,7 +251,7 @@ bool DrvInfo::queryMetaBool(const string & name, bool def) } -void DrvInfo::setMeta(const string & name, Value * v) +void DrvInfo::setMeta(const std::string & name, Value * v) { getMeta(); auto attrs = state->buildBindings(1 + (meta ? meta->size() : 0)); @@ -274,7 +274,7 @@ typedef std::set Done; The result boolean indicates whether it makes sense for the caller to recursively search for derivations in `v'. */ static bool getDerivation(EvalState & state, Value & v, - const string & attrPath, DrvInfos & drvs, Done & done, + const std::string & attrPath, DrvInfos & drvs, Done & done, bool ignoreAssertionFailures) { try { @@ -311,7 +311,7 @@ std::optional getDerivation(EvalState & state, Value & v, } -static string addToPath(const string & s1, const string & s2) +static std::string addToPath(const std::string & s1, const std::string & s2) { return s1.empty() ? s2 : s1 + "." + s2; } @@ -321,7 +321,7 @@ static std::regex attrRegex("[A-Za-z_][A-Za-z0-9-_+]*"); static void getDerivations(EvalState & state, Value & vIn, - const string & pathPrefix, Bindings & autoArgs, + const std::string & pathPrefix, Bindings & autoArgs, DrvInfos & drvs, Done & done, bool ignoreAssertionFailures) { @@ -346,7 +346,7 @@ static void getDerivations(EvalState & state, Value & vIn, debug("evaluating attribute '%1%'", i->name); if (!std::regex_match(std::string(i->name), attrRegex)) continue; - string pathPrefix2 = addToPath(pathPrefix, i->name); + std::string pathPrefix2 = addToPath(pathPrefix, i->name); if (combineChannels) getDerivations(state, *i->value, pathPrefix2, autoArgs, drvs, done, ignoreAssertionFailures); else if (getDerivation(state, *i->value, pathPrefix2, drvs, done, ignoreAssertionFailures)) { @@ -364,7 +364,7 @@ static void getDerivations(EvalState & state, Value & vIn, else if (v.type() == nList) { for (auto [n, elem] : enumerate(v.listItems())) { - string pathPrefix2 = addToPath(pathPrefix, fmt("%d", n)); + std::string pathPrefix2 = addToPath(pathPrefix, fmt("%d", n)); if (getDerivation(state, *elem, pathPrefix2, drvs, done, ignoreAssertionFailures)) getDerivations(state, *elem, pathPrefix2, autoArgs, drvs, done, ignoreAssertionFailures); } @@ -374,7 +374,7 @@ static void getDerivations(EvalState & state, Value & vIn, } -void getDerivations(EvalState & state, Value & v, const string & pathPrefix, +void getDerivations(EvalState & state, Value & v, const std::string & pathPrefix, Bindings & autoArgs, DrvInfos & drvs, bool ignoreAssertionFailures) { Done done; diff --git a/src/libexpr/get-drvs.hh b/src/libexpr/get-drvs.hh index 128354682..d13847785 100644 --- a/src/libexpr/get-drvs.hh +++ b/src/libexpr/get-drvs.hh @@ -12,16 +12,16 @@ namespace nix { struct DrvInfo { public: - typedef std::map Outputs; + typedef std::map Outputs; private: EvalState * state; - mutable string name; - mutable string system; - mutable string drvPath; - mutable std::optional outPath; - mutable string outputName; + mutable std::string name; + mutable std::string system; + mutable std::string drvPath; + mutable std::optional outPath; + mutable std::string outputName; Outputs outputs; bool failed = false; // set if we get an AssertionError @@ -33,36 +33,36 @@ private: bool checkMeta(Value & v); public: - string attrPath; /* path towards the derivation */ + std::string attrPath; /* path towards the derivation */ DrvInfo(EvalState & state) : state(&state) { }; - DrvInfo(EvalState & state, const string & attrPath, Bindings * attrs); + DrvInfo(EvalState & state, std::string attrPath, Bindings * attrs); DrvInfo(EvalState & state, ref store, const std::string & drvPathWithOutputs); - string queryName() const; - string querySystem() const; - string queryDrvPath() const; - string queryOutPath() const; - string queryOutputName() const; + std::string queryName() const; + std::string querySystem() const; + std::string queryDrvPath() const; + std::string queryOutPath() const; + std::string queryOutputName() const; /** Return the list of outputs. The "outputs to install" are determined by `meta.outputsToInstall`. */ Outputs queryOutputs(bool onlyOutputsToInstall = false); StringSet queryMetaNames(); - Value * queryMeta(const string & name); - string queryMetaString(const string & name); - NixInt queryMetaInt(const string & name, NixInt def); - NixFloat queryMetaFloat(const string & name, NixFloat def); - bool queryMetaBool(const string & name, bool def); - void setMeta(const string & name, Value * v); + Value * queryMeta(const std::string & name); + std::string queryMetaString(const std::string & name); + NixInt queryMetaInt(const std::string & name, NixInt def); + NixFloat queryMetaFloat(const std::string & name, NixFloat def); + bool queryMetaBool(const std::string & name, bool def); + void setMeta(const std::string & name, Value * v); /* MetaInfo queryMetaInfo(EvalState & state) const; MetaValue queryMetaInfo(EvalState & state, const string & name) const; */ - void setName(const string & s) { name = s; } - void setDrvPath(const string & s) { drvPath = s; } - void setOutPath(const string & s) { outPath = s; } + void setName(const std::string & s) { name = s; } + void setDrvPath(const std::string & s) { drvPath = s; } + void setOutPath(const std::string & s) { outPath = s; } void setFailed() { failed = true; }; bool hasFailed() { return failed; }; @@ -81,7 +81,7 @@ typedef std::list DrvInfos; std::optional getDerivation(EvalState & state, Value & v, bool ignoreAssertionFailures); -void getDerivations(EvalState & state, Value & v, const string & pathPrefix, +void getDerivations(EvalState & state, Value & v, const std::string & pathPrefix, Bindings & autoArgs, DrvInfos & drvs, bool ignoreAssertionFailures); diff --git a/src/libexpr/nixexpr.cc b/src/libexpr/nixexpr.cc index 27ea0f2ad..a2def65a6 100644 --- a/src/libexpr/nixexpr.cc +++ b/src/libexpr/nixexpr.cc @@ -16,10 +16,10 @@ std::ostream & operator << (std::ostream & str, const Expr & e) return str; } -static void showString(std::ostream & str, const string & s) +static void showString(std::ostream & str, std::string_view s) { str << '"'; - for (auto c : (string) s) + for (auto c : s) if (c == '"' || c == '\\' || c == '$') str << "\\" << c; else if (c == '\n') str << "\\n"; else if (c == '\r') str << "\\r"; @@ -28,7 +28,7 @@ static void showString(std::ostream & str, const string & s) str << '"'; } -static void showId(std::ostream & str, const string & s) +static void showId(std::ostream & str, std::string_view s) { if (s.empty()) str << "\"\""; @@ -218,7 +218,7 @@ std::ostream & operator << (std::ostream & str, const Pos & pos) auto f = format(ANSI_BOLD "%1%" ANSI_NORMAL ":%2%:%3%"); switch (pos.origin) { case foFile: - f % (string) pos.file; + f % (const std::string &) pos.file; break; case foStdin: case foString: @@ -234,7 +234,7 @@ std::ostream & operator << (std::ostream & str, const Pos & pos) } -string showAttrPath(const AttrPath & attrPath) +std::string showAttrPath(const AttrPath & attrPath) { std::ostringstream out; bool first = true; @@ -468,9 +468,9 @@ void ExprLambda::setName(Symbol & name) } -string ExprLambda::showNamePos() const +std::string ExprLambda::showNamePos() const { - return (format("%1% at %2%") % (name.set() ? "'" + (string) name + "'" : "anonymous function") % pos).str(); + return fmt("%1% at %2%", name.set() ? "'" + (std::string) name + "'" : "anonymous function", pos); } diff --git a/src/libexpr/nixexpr.hh b/src/libexpr/nixexpr.hh index e7f717eba..12b54b8eb 100644 --- a/src/libexpr/nixexpr.hh +++ b/src/libexpr/nixexpr.hh @@ -26,18 +26,21 @@ struct Pos FileOrigin origin; Symbol file; unsigned int line, column; - Pos() : origin(foString), line(0), column(0) { }; + + Pos() : origin(foString), line(0), column(0) { } Pos(FileOrigin origin, const Symbol & file, unsigned int line, unsigned int column) - : origin(origin), file(file), line(line), column(column) { }; + : origin(origin), file(file), line(line), column(column) { } + operator bool() const { return line != 0; } + bool operator < (const Pos & p2) const { if (!line) return p2.line; if (!p2.line) return false; - int d = ((string) file).compare((string) p2.file); + int d = ((const std::string &) file).compare((const std::string &) p2.file); if (d < 0) return true; if (d > 0) return false; if (line < p2.line) return true; @@ -68,7 +71,7 @@ struct AttrName typedef std::vector AttrPath; -string showAttrPath(const AttrPath & attrPath); +std::string showAttrPath(const AttrPath & attrPath); /* Abstract syntax of Nix expressions. */ @@ -110,7 +113,7 @@ struct ExprFloat : Expr struct ExprString : Expr { - string s; + std::string s; Value v; ExprString(std::string s) : s(std::move(s)) { v.mkString(this->s.data()); }; COMMON_METHODS @@ -119,9 +122,9 @@ struct ExprString : Expr struct ExprPath : Expr { - string s; + std::string s; Value v; - ExprPath(const string & s) : s(s) { v.mkPath(this->s.c_str()); }; + ExprPath(std::string s) : s(std::move(s)) { v.mkPath(this->s.c_str()); }; COMMON_METHODS Value * maybeThunk(EvalState & state, Env & env); }; @@ -249,7 +252,7 @@ struct ExprLambda : Expr { }; void setName(Symbol & name); - string showNamePos() const; + std::string showNamePos() const; inline bool hasFormals() const { return formals != nullptr; } COMMON_METHODS }; diff --git a/src/libexpr/parser.y b/src/libexpr/parser.y index e1d177c1f..919b9cfae 100644 --- a/src/libexpr/parser.y +++ b/src/libexpr/parser.y @@ -244,7 +244,7 @@ static Expr * stripIndentation(const Pos & pos, SymbolTable & symbols, es2->emplace_back(i->first, e); }; const auto trimString = [&] (const StringToken & t) { - string s2; + std::string s2; for (size_t j = 0; j < t.l; ++j) { if (atStartOfLine) { if (t.p[j] == ' ') { @@ -268,9 +268,9 @@ static Expr * stripIndentation(const Pos & pos, SymbolTable & symbols, /* Remove the last line if it is empty and consists only of spaces. */ if (n == 1) { - string::size_type p = s2.find_last_of('\n'); - if (p != string::npos && s2.find_first_not_of(' ', p + 1) == string::npos) - s2 = string(s2, 0, p + 1); + std::string::size_type p = s2.find_last_of('\n'); + if (p != std::string::npos && s2.find_first_not_of(' ', p + 1) == std::string::npos) + s2 = std::string(s2, 0, p + 1); } es2->emplace_back(i->first, new ExprString(s2)); @@ -466,7 +466,7 @@ expr_simple $$ = new ExprConcatStrings(CUR_POS, false, $2); } | SPATH { - string path($1.p + 1, $1.l - 2); + std::string path($1.p + 1, $1.l - 2); $$ = new ExprCall(CUR_POS, new ExprVar(data->symbols.create("__findFile")), {new ExprVar(data->symbols.create("__nixPath")), @@ -479,7 +479,7 @@ expr_simple .msg = hintfmt("URL literals are disabled"), .errPos = CUR_POS }); - $$ = new ExprString(string($1)); + $$ = new ExprString(std::string($1)); } | '(' expr ')' { $$ = $2; } /* Let expressions `let {..., body = ...}' are just desugared @@ -494,19 +494,19 @@ expr_simple ; string_parts - : STR { $$ = new ExprString(string($1)); } + : STR { $$ = new ExprString(std::string($1)); } | string_parts_interpolated { $$ = new ExprConcatStrings(CUR_POS, true, $1); } | { $$ = new ExprString(""); } ; string_parts_interpolated : string_parts_interpolated STR - { $$ = $1; $1->emplace_back(makeCurPos(@2, data), new ExprString(string($2))); } + { $$ = $1; $1->emplace_back(makeCurPos(@2, data), new ExprString(std::string($2))); } | string_parts_interpolated DOLLAR_CURLY expr '}' { $$ = $1; $1->emplace_back(makeCurPos(@2, data), $3); } | DOLLAR_CURLY expr '}' { $$ = new std::vector >; $$->emplace_back(makeCurPos(@1, data), $2); } | STR DOLLAR_CURLY expr '}' { $$ = new std::vector >; - $$->emplace_back(makeCurPos(@1, data), new ExprString(string($1))); + $$->emplace_back(makeCurPos(@1, data), new ExprString(std::string($1))); $$->emplace_back(makeCurPos(@2, data), $3); } ; @@ -520,7 +520,7 @@ path_start $$ = new ExprPath(path); } | HPATH { - Path path(getHome() + string($1.p + 1, $1.l - 1)); + Path path(getHome() + std::string($1.p + 1, $1.l - 1)); $$ = new ExprPath(path); } ; @@ -738,16 +738,16 @@ Expr * EvalState::parseStdin() } -void EvalState::addToSearchPath(const string & s) +void EvalState::addToSearchPath(const std::string & s) { size_t pos = s.find('='); - string prefix; + std::string prefix; Path path; - if (pos == string::npos) { + if (pos == std::string::npos) { path = s; } else { - prefix = string(s, 0, pos); - path = string(s, pos + 1); + prefix = std::string(s, 0, pos); + path = std::string(s, pos + 1); } searchPath.emplace_back(prefix, path); diff --git a/src/libexpr/primops.cc b/src/libexpr/primops.cc index daf679a5a..aa22c3b61 100644 --- a/src/libexpr/primops.cc +++ b/src/libexpr/primops.cc @@ -141,7 +141,7 @@ static void mkOutputString( BindingsBuilder & attrs, const StorePath & drvPath, const BasicDerivation & drv, - const std::pair & o) + const std::pair & o) { auto optOutputPath = o.second.path(*state.store, drv.name, o.first); attrs.alloc(o.first).mkString( @@ -314,7 +314,7 @@ void prim_importNative(EvalState & state, const Pos & pos, Value * * args, Value { auto path = realisePath(state, pos, *args[0]); - string sym(state.forceStringNoCtx(*args[1], pos)); + std::string sym(state.forceStringNoCtx(*args[1], pos)); void *handle = dlopen(path.c_str(), RTLD_LAZY | RTLD_LOCAL); if (!handle) @@ -386,7 +386,7 @@ void prim_exec(EvalState & state, const Pos & pos, Value * * args, Value & v) static void prim_typeOf(EvalState & state, const Pos & pos, Value * * args, Value & v) { state.forceValue(*args[0], pos); - string t; + std::string t; switch (args[0]->type()) { case nInt: t = "int"; break; case nBool: t = "bool"; break; @@ -707,7 +707,7 @@ static RegisterPrimOp primop_abort({ .fun = [](EvalState & state, const Pos & pos, Value * * args, Value & v) { PathSet context; - string s = state.coerceToString(pos, *args[0], context).toOwned(); + auto s = state.coerceToString(pos, *args[0], context).toOwned(); throw Abort("evaluation aborted with the following error message: '%1%'", s); } }); @@ -725,7 +725,7 @@ static RegisterPrimOp primop_throw({ .fun = [](EvalState & state, const Pos & pos, Value * * args, Value & v) { PathSet context; - string s = state.coerceToString(pos, *args[0], context).toOwned(); + auto s = state.coerceToString(pos, *args[0], context).toOwned(); throw ThrownError(s); } }); @@ -826,7 +826,7 @@ static RegisterPrimOp primop_tryEval({ /* Return an environment variable. Use with care. */ static void prim_getEnv(EvalState & state, const Pos & pos, Value * * args, Value & v) { - string name(state.forceStringNoCtx(*args[0], pos)); + std::string name(state.forceStringNoCtx(*args[0], pos)); v.mkString(evalSettings.restrictEval || evalSettings.pureEval ? "" : getEnv(name).value_or("")); } @@ -935,7 +935,7 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * * pos ); - string drvName; + std::string drvName; Pos & posDrvName(*attr->pos); try { drvName = state.forceStringNoCtx(*attr->value, pos); @@ -973,7 +973,7 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * * for (auto & i : args[0]->attrs->lexicographicOrder()) { if (i->name == state.sIgnoreNulls) continue; - const string & key = i->name; + const std::string & key = i->name; vomit("processing attribute '%1%'", key); auto handleHashMode = [&](const std::string_view s) { @@ -1031,7 +1031,7 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * * else if (i->name == state.sArgs) { state.forceList(*i->value, pos); for (auto elem : i->value->listItems()) { - string s = state.coerceToString(posDrvName, *elem, context, true).toOwned(); + auto s = state.coerceToString(posDrvName, *elem, context, true).toOwned(); drv.args.push_back(s); } } @@ -1118,7 +1118,7 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * * /* Handle derivation outputs of the form ‘!!’. */ else if (path.at(0) == '!') { - std::pair ctx = decodeContext(path); + auto ctx = decodeContext(path); drv.inputDrvs[state.store->parseStorePath(ctx.first)].insert(ctx.second); } @@ -1440,8 +1440,8 @@ static RegisterPrimOp primop_dirOf({ static void prim_readFile(EvalState & state, const Pos & pos, Value * * args, Value & v) { auto path = realisePath(state, pos, *args[0]); - string s = readFile(path); - if (s.find((char) 0) != string::npos) + auto s = readFile(path); + if (s.find((char) 0) != std::string::npos) throw Error("the contents of the file '%1%' cannot be represented as a Nix string", path); StorePathSet refs; if (state.store->isInStore(path)) { @@ -1474,7 +1474,7 @@ static void prim_findFile(EvalState & state, const Pos & pos, Value * * args, Va for (auto v2 : args[0]->listItems()) { state.forceAttrs(*v2, pos); - string prefix; + std::string prefix; Bindings::iterator i = v2->attrs->find(state.sPrefix); if (i != v2->attrs->end()) prefix = state.forceStringNoCtx(*i->value, pos); @@ -1488,7 +1488,7 @@ static void prim_findFile(EvalState & state, const Pos & pos, Value * * args, Va ); PathSet context; - string path = state.coerceToString(pos, *i->value, context, false, false).toOwned(); + auto path = state.coerceToString(pos, *i->value, context, false, false).toOwned(); try { auto rewrites = state.realiseContext(context); @@ -1754,8 +1754,8 @@ static RegisterPrimOp primop_fromJSON({ static void prim_toFile(EvalState & state, const Pos & pos, Value * * args, Value & v) { PathSet context; - string name(state.forceStringNoCtx(*args[0], pos)); - string contents(state.forceString(*args[1], context, pos)); + std::string name(state.forceStringNoCtx(*args[0], pos)); + std::string contents(state.forceString(*args[1], context, pos)); StorePathSet refs; @@ -1863,7 +1863,7 @@ static RegisterPrimOp primop_toFile({ static void addPath( EvalState & state, const Pos & pos, - const string & name, + const std::string & name, Path path, Value * filterFun, FileIngestionMethod method, @@ -2016,14 +2016,14 @@ static void prim_path(EvalState & state, const Pos & pos, Value * * args, Value { state.forceAttrs(*args[0], pos); Path path; - string name; + std::string name; Value * filterFun = nullptr; auto method = FileIngestionMethod::Recursive; std::optional expectedHash; PathSet context; for (auto & attr : *args[0]->attrs) { - const string & n(attr.name); + auto & n(attr.name); if (n == "path") path = state.coerceToPath(*attr.pos, *attr.value, context); else if (attr.name == state.sName) @@ -3616,7 +3616,7 @@ static void prim_concatStringsSep(EvalState & state, const Pos & pos, Value * * auto sep = state.forceString(*args[0], context, pos); state.forceList(*args[1], pos); - string res; + std::string res; res.reserve((args[1]->listSize() + 32) * sep.size()); bool first = true; @@ -3649,12 +3649,12 @@ static void prim_replaceStrings(EvalState & state, const Pos & pos, Value * * ar .errPos = pos }); - std::vector from; + std::vector from; from.reserve(args[0]->listSize()); for (auto elem : args[0]->listItems()) from.emplace_back(state.forceString(*elem, pos)); - std::vector> to; + std::vector> to; to.reserve(args[1]->listSize()); for (auto elem : args[1]->listItems()) { PathSet ctx; @@ -3665,7 +3665,7 @@ static void prim_replaceStrings(EvalState & state, const Pos & pos, Value * * ar PathSet context; auto s = state.forceString(*args[2], context, pos); - string res; + std::string res; // Loops one past last character to handle the case where 'from' contains an empty string. for (size_t p = 0; p <= s.size(); ) { bool found = false; diff --git a/src/libexpr/primops/context.cc b/src/libexpr/primops/context.cc index 654251c23..3701bd442 100644 --- a/src/libexpr/primops/context.cc +++ b/src/libexpr/primops/context.cc @@ -37,7 +37,7 @@ static void prim_unsafeDiscardOutputDependency(EvalState & state, const Pos & po PathSet context2; for (auto & p : context) - context2.insert(p.at(0) == '=' ? string(p, 1) : p); + context2.insert(p.at(0) == '=' ? std::string(p, 1) : p); v.mkString(*s, context2); } @@ -76,13 +76,13 @@ static void prim_getContext(EvalState & state, const Pos & pos, Value * * args, auto contextInfos = std::map(); for (const auto & p : context) { Path drv; - string output; + std::string output; const Path * path = &p; if (p.at(0) == '=') { - drv = string(p, 1); + drv = std::string(p, 1); path = &drv; } else if (p.at(0) == '!') { - std::pair ctx = decodeContext(p); + std::pair ctx = decodeContext(p); drv = ctx.first; output = ctx.second; path = &drv; @@ -166,7 +166,7 @@ static void prim_appendContext(EvalState & state, const Pos & pos, Value * * arg .errPos = *i.pos }); } - context.insert("=" + string(i.name)); + context.insert("=" + std::string(i.name)); } } diff --git a/src/libexpr/primops/fetchMercurial.cc b/src/libexpr/primops/fetchMercurial.cc index c4e1a7bf0..b7f715859 100644 --- a/src/libexpr/primops/fetchMercurial.cc +++ b/src/libexpr/primops/fetchMercurial.cc @@ -62,7 +62,7 @@ static void prim_fetchMercurial(EvalState & state, const Pos & pos, Value * * ar fetchers::Attrs attrs; attrs.insert_or_assign("type", "hg"); attrs.insert_or_assign("url", url.find("://") != std::string::npos ? url : "file://" + url); - attrs.insert_or_assign("name", string(name)); + attrs.insert_or_assign("name", std::string(name)); if (ref) attrs.insert_or_assign("ref", *ref); if (rev) attrs.insert_or_assign("rev", rev->gitRev()); auto input = fetchers::Input::fromAttrs(std::move(attrs)); diff --git a/src/libexpr/primops/fetchTree.cc b/src/libexpr/primops/fetchTree.cc index 7496104b6..f3e3e70d8 100644 --- a/src/libexpr/primops/fetchTree.cc +++ b/src/libexpr/primops/fetchTree.cc @@ -186,7 +186,7 @@ static void prim_fetchTree(EvalState & state, const Pos & pos, Value * * args, V static RegisterPrimOp primop_fetchTree("fetchTree", 1, prim_fetchTree); static void fetch(EvalState & state, const Pos & pos, Value * * args, Value & v, - const string & who, bool unpack, std::string name) + const std::string & who, bool unpack, std::string name) { std::optional url; std::optional expectedHash; @@ -198,7 +198,7 @@ static void fetch(EvalState & state, const Pos & pos, Value * * args, Value & v, state.forceAttrs(*args[0], pos); for (auto & attr : *args[0]->attrs) { - string n(attr.name); + std::string n(attr.name); if (n == "url") url = state.forceStringNoCtx(*attr.value, *attr.pos); else if (n == "sha256") diff --git a/src/libexpr/primops/fromTOML.cc b/src/libexpr/primops/fromTOML.cc index c0e858b61..dd4280030 100644 --- a/src/libexpr/primops/fromTOML.cc +++ b/src/libexpr/primops/fromTOML.cc @@ -9,7 +9,7 @@ static void prim_fromTOML(EvalState & state, const Pos & pos, Value * * args, Va { auto toml = state.forceStringNoCtx(*args[0], pos); - std::istringstream tomlStream(string{toml}); + std::istringstream tomlStream(std::string{toml}); std::function visit; diff --git a/src/libexpr/value-to-xml.cc b/src/libexpr/value-to-xml.cc index a9fb60b0e..afeaf5694 100644 --- a/src/libexpr/value-to-xml.cc +++ b/src/libexpr/value-to-xml.cc @@ -9,7 +9,7 @@ namespace nix { -static XMLAttrs singletonAttrs(const string & name, const string & value) +static XMLAttrs singletonAttrs(const std::string & name, const std::string & value) { XMLAttrs attrs; attrs[name] = value; diff --git a/src/libfetchers/mercurial.cc b/src/libfetchers/mercurial.cc index 798369c7a..12cdecbc1 100644 --- a/src/libfetchers/mercurial.cc +++ b/src/libfetchers/mercurial.cc @@ -26,7 +26,7 @@ static RunOptions hgOptions(const Strings & args) } // runProgram wrapper that uses hgOptions instead of stock RunOptions. -static string runHg(const Strings & args, const std::optional & input = {}) +static std::string runHg(const Strings & args, const std::optional & input = {}) { RunOptions opts = hgOptions(args); opts.input = input; @@ -254,7 +254,7 @@ struct MercurialInputScheme : InputScheme runHg({ "pull", "-R", cacheDir, "--", actualUrl }); } catch (ExecError & e) { - string transJournal = cacheDir + "/.hg/store/journal"; + auto transJournal = cacheDir + "/.hg/store/journal"; /* hg throws "abandoned transaction" error only if this file exists */ if (pathExists(transJournal)) { runHg({ "recover", "-R", cacheDir }); diff --git a/src/libmain/common-args.cc b/src/libmain/common-args.cc index c43e9ebd2..12f5403ea 100644 --- a/src/libmain/common-args.cc +++ b/src/libmain/common-args.cc @@ -4,7 +4,7 @@ namespace nix { -MixCommonArgs::MixCommonArgs(const string & programName) +MixCommonArgs::MixCommonArgs(const std::string & programName) : programName(programName) { addFlag({ diff --git a/src/libmain/common-args.hh b/src/libmain/common-args.hh index 31bdf527a..25453b8c6 100644 --- a/src/libmain/common-args.hh +++ b/src/libmain/common-args.hh @@ -11,8 +11,8 @@ class MixCommonArgs : public virtual Args { void initialFlagsProcessed() override; public: - string programName; - MixCommonArgs(const string & programName); + std::string programName; + MixCommonArgs(const std::string & programName); protected: virtual void pluginsInited() {} }; diff --git a/src/libmain/shared.cc b/src/libmain/shared.cc index f605184bb..47fc7ab2e 100644 --- a/src/libmain/shared.cc +++ b/src/libmain/shared.cc @@ -94,7 +94,7 @@ void printMissing(ref store, const StorePathSet & willBuild, } -string getArg(const string & opt, +std::string getArg(const std::string & opt, Strings::iterator & i, const Strings::iterator & end) { ++i; @@ -227,6 +227,8 @@ LegacyArgs::LegacyArgs(const std::string & programName, std::function parseArg) : MixCommonArgs(programName), parseArg(parseArg) { + printError("FOO %s", programName); + addFlag({ .longName = "no-build-output", .shortName = 'Q', @@ -322,14 +324,14 @@ void parseCmdLine(int argc, char * * argv, } -void parseCmdLine(const string & programName, const Strings & args, +void parseCmdLine(const std::string & programName, const Strings & args, std::function parseArg) { LegacyArgs(programName, parseArg).parseCmdline(args); } -void printVersion(const string & programName) +void printVersion(const std::string & programName) { std::cout << format("%1% (Nix) %2%") % programName % nixVersion << std::endl; if (verbosity > lvlInfo) { @@ -352,7 +354,7 @@ void printVersion(const string & programName) } -void showManPage(const string & name) +void showManPage(const std::string & name) { restoreProcessContext(); setenv("MANPATH", settings.nixManDir.c_str(), 1); @@ -361,13 +363,13 @@ void showManPage(const string & name) } -int handleExceptions(const string & programName, std::function fun) +int handleExceptions(const std::string & programName, std::function fun) { ReceiveInterrupts receiveInterrupts; // FIXME: need better place for this ErrorInfo::programName = baseNameOf(programName); - string error = ANSI_RED "error:" ANSI_NORMAL " "; + std::string error = ANSI_RED "error:" ANSI_NORMAL " "; try { try { fun(); @@ -407,7 +409,7 @@ RunPager::RunPager() if (!isatty(STDOUT_FILENO)) return; char * pager = getenv("NIX_PAGER"); if (!pager) pager = getenv("PAGER"); - if (pager && ((string) pager == "" || (string) pager == "cat")) return; + if (pager && ((std::string) pager == "" || (std::string) pager == "cat")) return; Pipe toPager; toPager.create(); diff --git a/src/libmain/shared.hh b/src/libmain/shared.hh index ed012959b..0cc56d47d 100644 --- a/src/libmain/shared.hh +++ b/src/libmain/shared.hh @@ -22,7 +22,7 @@ public: virtual ~Exit(); }; -int handleExceptions(const string & programName, std::function fun); +int handleExceptions(const std::string & programName, std::function fun); /* Don't forget to call initPlugins() after settings are initialized! */ void initNix(); @@ -30,10 +30,10 @@ void initNix(); void parseCmdLine(int argc, char * * argv, std::function parseArg); -void parseCmdLine(const string & programName, const Strings & args, +void parseCmdLine(const std::string & programName, const Strings & args, std::function parseArg); -void printVersion(const string & programName); +void printVersion(const std::string & programName); /* Ugh. No better place to put this. */ void printGCWarning(); @@ -50,10 +50,10 @@ void printMissing(ref store, const StorePathSet & willBuild, const StorePathSet & willSubstitute, const StorePathSet & unknown, uint64_t downloadSize, uint64_t narSize, Verbosity lvl = lvlInfo); -string getArg(const string & opt, +std::string getArg(const std::string & opt, Strings::iterator & i, const Strings::iterator & end); -template N getIntArg(const string & opt, +template N getIntArg(const std::string & opt, Strings::iterator & i, const Strings::iterator & end, bool allowUnit) { ++i; @@ -76,7 +76,7 @@ struct LegacyArgs : public MixCommonArgs /* Show the manual page for the specified program. */ -void showManPage(const string & name); +void showManPage(const std::string & name); /* The constructor of this class starts a pager if stdout is a terminal and $PAGER is set. Stdout is redirected to the pager. */ @@ -96,7 +96,7 @@ extern volatile ::sig_atomic_t blockInt; /* GC helpers. */ -string showBytes(uint64_t bytes); +std::string showBytes(uint64_t bytes); struct GCResults; diff --git a/src/libstore/binary-cache-store.cc b/src/libstore/binary-cache-store.cc index b3fd991a1..9226c4e19 100644 --- a/src/libstore/binary-cache-store.cc +++ b/src/libstore/binary-cache-store.cc @@ -385,8 +385,14 @@ void BinaryCacheStore::queryPathInfoUncached(const StorePath & storePath, }}); } -StorePath BinaryCacheStore::addToStore(const string & name, const Path & srcPath, - FileIngestionMethod method, HashType hashAlgo, PathFilter & filter, RepairFlag repair, const StorePathSet & references) +StorePath BinaryCacheStore::addToStore( + std::string_view name, + const Path & srcPath, + FileIngestionMethod method, + HashType hashAlgo, + PathFilter & filter, + RepairFlag repair, + const StorePathSet & references) { /* FIXME: Make BinaryCacheStore::addToStoreCommon support non-recursive+sha256 so we can just use the default @@ -418,8 +424,11 @@ StorePath BinaryCacheStore::addToStore(const string & name, const Path & srcPath })->path; } -StorePath BinaryCacheStore::addTextToStore(const string & name, const string & s, - const StorePathSet & references, RepairFlag repair) +StorePath BinaryCacheStore::addTextToStore( + std::string_view name, + std::string_view s, + const StorePathSet & references, + RepairFlag repair) { auto textHash = hashString(htSHA256, s); auto path = makeTextPath(name, textHash, references); diff --git a/src/libstore/binary-cache-store.hh b/src/libstore/binary-cache-store.hh index 5b5d064f3..9603a8caa 100644 --- a/src/libstore/binary-cache-store.hh +++ b/src/libstore/binary-cache-store.hh @@ -101,12 +101,20 @@ public: StorePath addToStoreFromDump(Source & dump, std::string_view name, FileIngestionMethod method, HashType hashAlgo, RepairFlag repair, const StorePathSet & references) override; - StorePath addToStore(const string & name, const Path & srcPath, - FileIngestionMethod method, HashType hashAlgo, - PathFilter & filter, RepairFlag repair, const StorePathSet & references) override; + StorePath addToStore( + std::string_view name, + const Path & srcPath, + FileIngestionMethod method, + HashType hashAlgo, + PathFilter & filter, + RepairFlag repair, + const StorePathSet & references) override; - StorePath addTextToStore(const string & name, const string & s, - const StorePathSet & references, RepairFlag repair) override; + StorePath addTextToStore( + std::string_view name, + std::string_view s, + const StorePathSet & references, + RepairFlag repair) override; void registerDrvOutput(const Realisation & info) override; diff --git a/src/libstore/build/derivation-goal.cc b/src/libstore/build/derivation-goal.cc index 27f8c6257..95da1841d 100644 --- a/src/libstore/build/derivation-goal.cc +++ b/src/libstore/build/derivation-goal.cc @@ -116,7 +116,7 @@ DerivationGoal::~DerivationGoal() } -string DerivationGoal::key() +std::string DerivationGoal::key() { /* Ensure that derivations get built in order of their name, i.e. a derivation named "aardvark" always comes before @@ -1013,7 +1013,7 @@ HookReply DerivationGoal::tryBuildHook() /* Read the first line of input, which should be a word indicating whether the hook wishes to perform the build. */ - string reply; + std::string reply; while (true) { auto s = [&]() { try { @@ -1025,8 +1025,8 @@ HookReply DerivationGoal::tryBuildHook() }(); if (handleJSONLogMessage(s, worker.act, worker.hook->activities, true)) ; - else if (string(s, 0, 2) == "# ") { - reply = string(s, 2); + else if (s.substr(0, 2) == "# ") { + reply = s.substr(2); break; } else { @@ -1140,10 +1140,10 @@ Path DerivationGoal::openLogFile() logDir = localStore->logDir; else logDir = settings.nixLogDir; - Path dir = fmt("%s/%s/%s/", logDir, LocalFSStore::drvsLogDir, string(baseName, 0, 2)); + Path dir = fmt("%s/%s/%s/", logDir, LocalFSStore::drvsLogDir, baseName.substr(0, 2)); createDirs(dir); - Path logFileName = fmt("%s/%s%s", dir, string(baseName, 2), + Path logFileName = fmt("%s/%s%s", dir, baseName.substr(2), settings.compressLog ? ".bz2" : ""); fdLogFile = open(logFileName.c_str(), O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC, 0666); @@ -1176,7 +1176,7 @@ bool DerivationGoal::isReadDesc(int fd) } -void DerivationGoal::handleChildOutput(int fd, const string & data) +void DerivationGoal::handleChildOutput(int fd, std::string_view data) { if (isReadDesc(fd)) { diff --git a/src/libstore/build/derivation-goal.hh b/src/libstore/build/derivation-goal.hh index e112542c7..d947482ef 100644 --- a/src/libstore/build/derivation-goal.hh +++ b/src/libstore/build/derivation-goal.hh @@ -145,7 +145,7 @@ struct DerivationGoal : public Goal void timedOut(Error && ex) override; - string key() override; + std::string key() override; void work() override; @@ -200,7 +200,7 @@ struct DerivationGoal : public Goal virtual bool isReadDesc(int fd); /* Callback used by the worker to write to the log. */ - void handleChildOutput(int fd, const string & data) override; + void handleChildOutput(int fd, std::string_view data) override; void handleEOF(int fd) override; void flushLine(); diff --git a/src/libstore/build/drv-output-substitution-goal.cc b/src/libstore/build/drv-output-substitution-goal.cc index b9602e696..e6e810cdd 100644 --- a/src/libstore/build/drv-output-substitution-goal.cc +++ b/src/libstore/build/drv-output-substitution-goal.cc @@ -137,7 +137,7 @@ void DrvOutputSubstitutionGoal::finished() amDone(ecSuccess); } -string DrvOutputSubstitutionGoal::key() +std::string DrvOutputSubstitutionGoal::key() { /* "a$" ensures substitution goals happen before derivation goals. */ diff --git a/src/libstore/build/drv-output-substitution-goal.hh b/src/libstore/build/drv-output-substitution-goal.hh index 67ae2624a..948dbda8f 100644 --- a/src/libstore/build/drv-output-substitution-goal.hh +++ b/src/libstore/build/drv-output-substitution-goal.hh @@ -51,7 +51,7 @@ public: void timedOut(Error && ex) override { abort(); }; - string key() override; + std::string key() override; void work() override; void handleEOF(int fd) override; diff --git a/src/libstore/build/goal.cc b/src/libstore/build/goal.cc index 7c985128b..d2420b107 100644 --- a/src/libstore/build/goal.cc +++ b/src/libstore/build/goal.cc @@ -5,8 +5,8 @@ namespace nix { bool CompareGoalPtrs::operator() (const GoalPtr & a, const GoalPtr & b) const { - string s1 = a->key(); - string s2 = b->key(); + std::string s1 = a->key(); + std::string s2 = b->key(); return s1 < s2; } diff --git a/src/libstore/build/goal.hh b/src/libstore/build/goal.hh index 0db0c1938..68e08bdf9 100644 --- a/src/libstore/build/goal.hh +++ b/src/libstore/build/goal.hh @@ -50,7 +50,7 @@ struct Goal : public std::enable_shared_from_this unsigned int nrIncompleteClosure; /* Name of this goal for debugging purposes. */ - string name; + std::string name; /* Whether the goal is finished. */ ExitCode exitCode; @@ -75,7 +75,7 @@ struct Goal : public std::enable_shared_from_this virtual void waiteeDone(GoalPtr waitee, ExitCode result); - virtual void handleChildOutput(int fd, const string & data) + virtual void handleChildOutput(int fd, std::string_view data) { abort(); } @@ -87,7 +87,7 @@ struct Goal : public std::enable_shared_from_this void trace(const FormatOrString & fs); - string getName() + std::string getName() { return name; } @@ -97,7 +97,7 @@ struct Goal : public std::enable_shared_from_this by the worker (important!), etc. */ virtual void timedOut(Error && ex) = 0; - virtual string key() = 0; + virtual std::string key() = 0; void amDone(ExitCode result, std::optional ex = {}); diff --git a/src/libstore/build/local-derivation-goal.cc b/src/libstore/build/local-derivation-goal.cc index 8861d2c7b..220f80602 100644 --- a/src/libstore/build/local-derivation-goal.cc +++ b/src/libstore/build/local-derivation-goal.cc @@ -481,12 +481,12 @@ void LocalDerivationGoal::startBuilder() temporary build directory. The text files have the format used by `nix-store --register-validity'. However, the deriver fields are left empty. */ - string s = get(drv->env, "exportReferencesGraph").value_or(""); + auto s = get(drv->env, "exportReferencesGraph").value_or(""); Strings ss = tokenizeString(s); if (ss.size() % 2 != 0) throw BuildError("odd number of tokens in 'exportReferencesGraph': '%1%'", s); for (Strings::iterator i = ss.begin(); i != ss.end(); ) { - string fileName = *i++; + auto fileName = *i++; static std::regex regex("[A-Za-z_][A-Za-z0-9_.-]*"); if (!std::regex_match(fileName, regex)) throw Error("invalid file name '%s' in 'exportReferencesGraph'", fileName); @@ -517,10 +517,10 @@ void LocalDerivationGoal::startBuilder() i.pop_back(); } size_t p = i.find('='); - if (p == string::npos) + if (p == std::string::npos) dirsInChroot[i] = {i, optional}; else - dirsInChroot[string(i, 0, p)] = {string(i, p + 1), optional}; + dirsInChroot[i.substr(0, p)] = {i.substr(p + 1), optional}; } dirsInChroot[tmpDirInSandbox] = tmpDir; @@ -671,9 +671,10 @@ void LocalDerivationGoal::startBuilder() auto state = stBegin; auto lines = runProgram(settings.preBuildHook, false, args); auto lastPos = std::string::size_type{0}; - for (auto nlPos = lines.find('\n'); nlPos != string::npos; - nlPos = lines.find('\n', lastPos)) { - auto line = std::string{lines, lastPos, nlPos - lastPos}; + for (auto nlPos = lines.find('\n'); nlPos != std::string::npos; + nlPos = lines.find('\n', lastPos)) + { + auto line = lines.substr(lastPos, nlPos - lastPos); lastPos = nlPos + 1; if (state == stBegin) { if (line == "extra-sandbox-paths" || line == "extra-chroot-dirs") { @@ -686,10 +687,10 @@ void LocalDerivationGoal::startBuilder() state = stBegin; } else { auto p = line.find('='); - if (p == string::npos) + if (p == std::string::npos) dirsInChroot[line] = line; else - dirsInChroot[string(line, 0, p)] = string(line, p + 1); + dirsInChroot[line.substr(0, p)] = line.substr(p + 1); } } } @@ -941,7 +942,7 @@ void LocalDerivationGoal::startBuilder() /* Check if setting up the build environment failed. */ std::vector msgs; while (true) { - string msg = [&]() { + std::string msg = [&]() { try { return readLine(builderOut.readSide.get()); } catch (Error & e) { @@ -953,8 +954,8 @@ void LocalDerivationGoal::startBuilder() throw; } }(); - if (string(msg, 0, 1) == "\2") break; - if (string(msg, 0, 1) == "\1") { + if (msg.substr(0, 1) == "\2") break; + if (msg.substr(0, 1) == "\1") { FdSource source(builderOut.readSide.get()); auto ex = readError(source); ex.addTrace({}, "while setting up the build environment"); @@ -990,7 +991,7 @@ void LocalDerivationGoal::initTmpDir() { env[i.first] = i.second; } else { auto hash = hashString(htSHA256, i.first); - string fn = ".attr-" + hash.to_string(Base32, false); + std::string fn = ".attr-" + hash.to_string(Base32, false); Path p = tmpDir + "/" + fn; writeFile(p, rewriteStrings(i.second, inputRewrites)); chownToBuilder(p); @@ -1081,7 +1082,7 @@ void LocalDerivationGoal::writeStructuredAttrs() for (auto & [i, v] : json["outputs"].get()) { /* The placeholder must have a rewrite, so we use it to cover both the cases where we know or don't know the output path ahead of time. */ - rewritten[i] = rewriteStrings(v, inputRewrites); + rewritten[i] = rewriteStrings((std::string) v, inputRewrites); } json["outputs"] = rewritten; @@ -1187,10 +1188,14 @@ struct RestrictedStore : public virtual RestrictedStoreConfig, public virtual Lo std::optional queryPathFromHashPart(const std::string & hashPart) override { throw Error("queryPathFromHashPart"); } - StorePath addToStore(const string & name, const Path & srcPath, - FileIngestionMethod method = FileIngestionMethod::Recursive, HashType hashAlgo = htSHA256, - PathFilter & filter = defaultPathFilter, RepairFlag repair = NoRepair, - const StorePathSet & references = StorePathSet()) override + StorePath addToStore( + std::string_view name, + const Path & srcPath, + FileIngestionMethod method, + HashType hashAlgo, + PathFilter & filter, + RepairFlag repair, + const StorePathSet & references) override { throw Error("addToStore"); } void addToStore(const ValidPathInfo & info, Source & narSource, @@ -1200,17 +1205,24 @@ struct RestrictedStore : public virtual RestrictedStoreConfig, public virtual Lo goal.addDependency(info.path); } - StorePath addTextToStore(const string & name, const string & s, - const StorePathSet & references, RepairFlag repair = NoRepair) override + StorePath addTextToStore( + std::string_view name, + std::string_view s, + const StorePathSet & references, + RepairFlag repair = NoRepair) override { auto path = next->addTextToStore(name, s, references, repair); goal.addDependency(path); return path; } - StorePath addToStoreFromDump(Source & dump, std::string_view name, - FileIngestionMethod method = FileIngestionMethod::Recursive, HashType hashAlgo = htSHA256, RepairFlag repair = NoRepair, - const StorePathSet & references = StorePathSet()) override + StorePath addToStoreFromDump( + Source & dump, + std::string_view name, + FileIngestionMethod method, + HashType hashAlgo, + RepairFlag repair, + const StorePathSet & references) override { auto path = next->addToStoreFromDump(dump, name, method, hashAlgo, repair, references); goal.addDependency(path); @@ -1992,7 +2004,7 @@ void LocalDerivationGoal::runChild() args.push_back(rewriteStrings(i, inputRewrites)); /* Indicate that we managed to set up the build environment. */ - writeFull(STDERR_FILENO, string("\2\n")); + writeFull(STDERR_FILENO, std::string("\2\n")); /* Execute the program. This should not return. */ if (drv->isBuiltin()) { @@ -2010,7 +2022,7 @@ void LocalDerivationGoal::runChild() else if (drv->builder == "builtin:unpack-channel") builtinUnpackChannel(drv2); else - throw Error("unsupported builtin builder '%1%'", string(drv->builder, 8)); + throw Error("unsupported builtin builder '%1%'", drv->builder.substr(8)); _exit(0); } catch (std::exception & e) { writeFull(STDERR_FILENO, e.what() + std::string("\n")); @@ -2694,7 +2706,7 @@ void LocalDerivationGoal::checkOutputs(const std::map & out } if (!badPaths.empty()) { - string badPathsStr; + std::string badPathsStr; for (auto & i : badPaths) { badPathsStr += "\n "; badPathsStr += worker.store.printStorePath(i); diff --git a/src/libstore/build/local-derivation-goal.hh b/src/libstore/build/local-derivation-goal.hh index bfdf91d89..2d1222d2f 100644 --- a/src/libstore/build/local-derivation-goal.hh +++ b/src/libstore/build/local-derivation-goal.hh @@ -58,7 +58,7 @@ struct LocalDerivationGoal : public DerivationGoal typedef map DirsInChroot; // maps target path to source path DirsInChroot dirsInChroot; - typedef map Environment; + typedef map Environment; Environment env; #if __APPLE__ diff --git a/src/libstore/build/substitution-goal.cc b/src/libstore/build/substitution-goal.cc index 5ecf1da7e..c1bb1941d 100644 --- a/src/libstore/build/substitution-goal.cc +++ b/src/libstore/build/substitution-goal.cc @@ -272,7 +272,7 @@ void PathSubstitutionGoal::finished() } -void PathSubstitutionGoal::handleChildOutput(int fd, const string & data) +void PathSubstitutionGoal::handleChildOutput(int fd, std::string_view data) { } diff --git a/src/libstore/build/substitution-goal.hh b/src/libstore/build/substitution-goal.hh index 70c806d23..d8399d2a8 100644 --- a/src/libstore/build/substitution-goal.hh +++ b/src/libstore/build/substitution-goal.hh @@ -59,7 +59,7 @@ public: void timedOut(Error && ex) override { abort(); }; - string key() override + std::string key() override { /* "a$" ensures substitution goals happen before derivation goals. */ @@ -77,7 +77,7 @@ public: void finished(); /* Callback used by the worker to write to the log. */ - void handleChildOutput(int fd, const string & data) override; + void handleChildOutput(int fd, std::string_view data) override; void handleEOF(int fd) override; void cleanup() override; diff --git a/src/libstore/build/worker.cc b/src/libstore/build/worker.cc index 0a6108233..f72c1cc9c 100644 --- a/src/libstore/build/worker.cc +++ b/src/libstore/build/worker.cc @@ -394,7 +394,7 @@ void Worker::waitForInput() } else { printMsg(lvlVomit, "%1%: read %2% bytes", goal->getName(), rd); - string data((char *) buffer.data(), rd); + std::string data((char *) buffer.data(), rd); j->lastOutput = after; goal->handleChildOutput(k, data); } diff --git a/src/libstore/builtins/buildenv.cc b/src/libstore/builtins/buildenv.cc index e88fc687a..25d015cb9 100644 --- a/src/libstore/builtins/buildenv.cc +++ b/src/libstore/builtins/buildenv.cc @@ -123,7 +123,7 @@ void buildProfile(const Path & out, Packages && pkgs) createLinks(state, pkgDir, out, priority); try { - for (const auto & p : tokenizeString>( + for (const auto & p : tokenizeString>( readFile(pkgDir + "/nix-support/propagated-user-env-packages"), " \n")) if (!done.count(p)) postponed.insert(p); @@ -161,7 +161,7 @@ void buildProfile(const Path & out, Packages && pkgs) void builtinBuildenv(const BasicDerivation & drv) { - auto getAttr = [&](const string & name) { + auto getAttr = [&](const std::string & name) { auto i = drv.env.find(name); if (i == drv.env.end()) throw Error("attribute '%s' missing", name); return i->second; diff --git a/src/libstore/builtins/fetchurl.cc b/src/libstore/builtins/fetchurl.cc index 4fb5d8a06..af3dfc409 100644 --- a/src/libstore/builtins/fetchurl.cc +++ b/src/libstore/builtins/fetchurl.cc @@ -16,7 +16,7 @@ void builtinFetchurl(const BasicDerivation & drv, const std::string & netrcData) writeFile(settings.netrcFile, netrcData, 0600); } - auto getAttr = [&](const string & name) { + auto getAttr = [&](const std::string & name) { auto i = drv.env.find(name); if (i == drv.env.end()) throw Error("attribute '%s' missing", name); return i->second; diff --git a/src/libstore/builtins/unpack-channel.cc b/src/libstore/builtins/unpack-channel.cc index d18e3ddaf..426d58a53 100644 --- a/src/libstore/builtins/unpack-channel.cc +++ b/src/libstore/builtins/unpack-channel.cc @@ -5,7 +5,7 @@ namespace nix { void builtinUnpackChannel(const BasicDerivation & drv) { - auto getAttr = [&](const string & name) { + auto getAttr = [&](const std::string & name) { auto i = drv.env.find(name); if (i == drv.env.end()) throw Error("attribute '%s' missing", name); return i->second; diff --git a/src/libstore/daemon.cc b/src/libstore/daemon.cc index 1ddd1a4d5..2ba03f0dd 100644 --- a/src/libstore/daemon.cc +++ b/src/libstore/daemon.cc @@ -479,8 +479,8 @@ static void performOp(TunnelLogger * logger, ref store, } case wopAddTextToStore: { - string suffix = readString(from); - string s = readString(from); + std::string suffix = readString(from); + std::string s = readString(from); auto refs = worker_proto::read(*store, from, Phantom {}); logger->startWork(); auto path = store->addTextToStore(suffix, s, refs, NoRepair); @@ -698,8 +698,8 @@ static void performOp(TunnelLogger * logger, ref store, if (GET_PROTOCOL_MINOR(clientVersion) >= 12) { unsigned int n = readInt(from); for (unsigned int i = 0; i < n; i++) { - string name = readString(from); - string value = readString(from); + auto name = readString(from); + auto value = readString(from); clientSettings.overrides.emplace(name, value); } } diff --git a/src/libstore/derivations.cc b/src/libstore/derivations.cc index 40af6a775..a49be0057 100644 --- a/src/libstore/derivations.cc +++ b/src/libstore/derivations.cc @@ -82,7 +82,7 @@ bool derivationIsImpure(DerivationType dt) { bool BasicDerivation::isBuiltin() const { - return string(builder, 0, 8) == "builtin:"; + return builder.substr(0, 8) == "builtin:"; } @@ -104,19 +104,19 @@ StorePath writeDerivation(Store & store, /* Read string `s' from stream `str'. */ -static void expect(std::istream & str, const string & s) +static void expect(std::istream & str, std::string_view s) { char s2[s.size()]; str.read(s2, s.size()); - if (string(s2, s.size()) != s) + if (std::string(s2, s.size()) != s) throw FormatError("expected string '%1%'", s); } /* Read a C-style string from stream `str'. */ -static string parseString(std::istream & str) +static std::string parseString(std::istream & str) { - string res; + std::string res; expect(str, "\""); int c; while ((c = str.get()) != '"') @@ -172,7 +172,7 @@ static DerivationOutput parseDerivationOutput(const Store & store, { if (hashAlgo != "") { auto method = FileIngestionMethod::Flat; - if (string(hashAlgo, 0, 2) == "r:") { + if (hashAlgo.substr(0, 2) == "r:") { method = FileIngestionMethod::Recursive; hashAlgo = hashAlgo.substr(2); } @@ -260,8 +260,8 @@ Derivation parseDerivation(const Store & store, std::string && s, std::string_vi /* Parse the environment variables. */ expect(str, ",["); while (!endOfList(str)) { - expect(str, "("); string name = parseString(str); - expect(str, ","); string value = parseString(str); + expect(str, "("); auto name = parseString(str); + expect(str, ","); auto value = parseString(str); expect(str, ")"); drv.env[name] = value; } @@ -271,7 +271,7 @@ Derivation parseDerivation(const Store & store, std::string && s, std::string_vi } -static void printString(string & res, std::string_view s) +static void printString(std::string & res, std::string_view s) { boost::container::small_vector buffer; buffer.reserve(s.size() * 2 + 2); @@ -289,7 +289,7 @@ static void printString(string & res, std::string_view s) } -static void printUnquotedString(string & res, std::string_view s) +static void printUnquotedString(std::string & res, std::string_view s) { res += '"'; res.append(s); @@ -298,7 +298,7 @@ static void printUnquotedString(string & res, std::string_view s) template -static void printStrings(string & res, ForwardIterator i, ForwardIterator j) +static void printStrings(std::string & res, ForwardIterator i, ForwardIterator j) { res += '['; bool first = true; @@ -311,7 +311,7 @@ static void printStrings(string & res, ForwardIterator i, ForwardIterator j) template -static void printUnquotedStrings(string & res, ForwardIterator i, ForwardIterator j) +static void printUnquotedStrings(std::string & res, ForwardIterator i, ForwardIterator j) { res += '['; bool first = true; @@ -323,10 +323,10 @@ static void printUnquotedStrings(string & res, ForwardIterator i, ForwardIterato } -string Derivation::unparse(const Store & store, bool maskOutputs, +std::string Derivation::unparse(const Store & store, bool maskOutputs, std::map * actualInputs) const { - string s; + std::string s; s.reserve(65536); s += "Derive(["; @@ -401,7 +401,7 @@ string Derivation::unparse(const Store & store, bool maskOutputs, // FIXME: remove -bool isDerivation(const string & fileName) +bool isDerivation(const std::string & fileName) { return hasSuffix(fileName, drvExtension); } @@ -593,7 +593,7 @@ std::map staticOutputHashes(Store & store, const Derivation & } -bool wantOutput(const string & output, const std::set & wanted) +bool wantOutput(const std::string & output, const std::set & wanted) { return wanted.empty() || wanted.find(output) != wanted.end(); } diff --git a/src/libstore/derivations.hh b/src/libstore/derivations.hh index a644cec60..132de82b6 100644 --- a/src/libstore/derivations.hh +++ b/src/libstore/derivations.hh @@ -59,21 +59,19 @@ struct DerivationOutput std::optional path(const Store & store, std::string_view drvName, std::string_view outputName) const; }; -typedef std::map DerivationOutputs; +typedef std::map DerivationOutputs; /* These are analogues to the previous DerivationOutputs data type, but they also contains, for each output, the (optional) store path in which it would be written. To calculate values of these types, see the corresponding functions in BasicDerivation */ -typedef std::map>> +typedef std::map>> DerivationOutputsAndOptPaths; /* For inputs that are sub-derivations, we specify exactly which output IDs we are interested in. */ typedef std::map DerivationInputs; -typedef std::map StringPairs; - enum struct DerivationType : uint8_t { InputAddressed, DeferredInputAddressed, @@ -103,7 +101,7 @@ struct BasicDerivation { DerivationOutputs outputs; /* keyed on symbolic IDs */ StorePathSet inputSrcs; /* inputs that are sources */ - string platform; + std::string platform; Path builder; Strings args; StringPairs env; @@ -164,7 +162,7 @@ StorePath writeDerivation(Store & store, Derivation parseDerivation(const Store & store, std::string && s, std::string_view name); // FIXME: remove -bool isDerivation(const string & fileName); +bool isDerivation(const std::string & fileName); /* Calculate the name that will be used for the store path for this output. @@ -222,7 +220,7 @@ typedef std::map DrvHashes; // FIXME: global, though at least thread-safe. extern Sync drvHashes; -bool wantOutput(const string & output, const std::set & wanted); +bool wantOutput(const std::string & output, const std::set & wanted); struct Source; struct Sink; diff --git a/src/libstore/derived-path.cc b/src/libstore/derived-path.cc index 3d188e981..194489580 100644 --- a/src/libstore/derived-path.cc +++ b/src/libstore/derived-path.cc @@ -75,9 +75,9 @@ DerivedPath::Built DerivedPath::Built::parse(const Store & store, std::string_vi assert(n != s.npos); auto drvPath = store.parseStorePath(s.substr(0, n)); auto outputsS = s.substr(n + 1); - std::set outputs; + std::set outputs; if (outputsS != "*") - outputs = tokenizeString>(outputsS, ","); + outputs = tokenizeString>(outputsS, ","); return {drvPath, outputs}; } diff --git a/src/libstore/dummy-store.cc b/src/libstore/dummy-store.cc index 62dc21c59..b4fbe0b70 100644 --- a/src/libstore/dummy-store.cc +++ b/src/libstore/dummy-store.cc @@ -21,7 +21,7 @@ struct DummyStore : public virtual DummyStoreConfig, public virtual Store , Store(params) { } - string getUri() override + std::string getUri() override { return *uriSchemes().begin(); } @@ -43,8 +43,11 @@ struct DummyStore : public virtual DummyStoreConfig, public virtual Store RepairFlag repair, CheckSigsFlag checkSigs) override { unsupported("addToStore"); } - StorePath addTextToStore(const string & name, const string & s, - const StorePathSet & references, RepairFlag repair) override + StorePath addTextToStore( + std::string_view name, + std::string_view s, + const StorePathSet & references, + RepairFlag repair) override { unsupported("addTextToStore"); } void narFromPath(const StorePath & path, Sink & sink) override diff --git a/src/libstore/filetransfer.cc b/src/libstore/filetransfer.cc index 76fed11db..255b42c49 100644 --- a/src/libstore/filetransfer.cc +++ b/src/libstore/filetransfer.cc @@ -33,12 +33,12 @@ FileTransferSettings fileTransferSettings; static GlobalConfig::Register rFileTransferSettings(&fileTransferSettings); -std::string resolveUri(const std::string & uri) +std::string resolveUri(std::string_view uri) { if (uri.compare(0, 8, "channel:") == 0) - return "https://nixos.org/channels/" + std::string(uri, 8) + "/nixexprs.tar.xz"; + return "https://nixos.org/channels/" + std::string(uri.substr(8)) + "/nixexprs.tar.xz"; else - return uri; + return std::string(uri); } struct curlFileTransfer : public FileTransfer @@ -197,15 +197,15 @@ struct curlFileTransfer : public FileTransfer result.etag = ""; result.data.clear(); result.bodySize = 0; - statusMsg = trim(match[1]); + statusMsg = trim((std::string &) match[1]); acceptRanges = false; encoding = ""; } else { auto i = line.find(':'); - if (i != string::npos) { - string name = toLower(trim(string(line, 0, i))); + if (i != std::string::npos) { + std::string name = toLower(trim(line.substr(0, i))); if (name == "etag") { - result.etag = trim(string(line, i + 1)); + result.etag = trim(line.substr(i + 1)); /* Hack to work around a GitHub bug: it sends ETags, but ignores If-None-Match. So if we get the expected ETag on a 200 response, then shut @@ -218,8 +218,8 @@ struct curlFileTransfer : public FileTransfer return 0; } } else if (name == "content-encoding") - encoding = trim(string(line, i + 1)); - else if (name == "accept-ranges" && toLower(trim(std::string(line, i + 1))) == "bytes") + encoding = trim(line.substr(i + 1)); + else if (name == "accept-ranges" && toLower(trim(line.substr(i + 1))) == "bytes") acceptRanges = true; } } @@ -866,18 +866,18 @@ FileTransferError::FileTransferError(FileTransfer::Error error, std::optionalsize() < 1024 || response->find("") != string::npos)) + if (response && (response->size() < 1024 || response->find("") != std::string::npos)) err.msg = hintfmt("%1%\n\nresponse body:\n\n%2%", normaltxt(hf.str()), chomp(*response)); else err.msg = hf; } -bool isUri(const string & s) +bool isUri(std::string_view s) { if (s.compare(0, 8, "channel:") == 0) return true; size_t pos = s.find("://"); - if (pos == string::npos) return false; - string scheme(s, 0, pos); + if (pos == std::string::npos) return false; + std::string scheme(s, 0, pos); return scheme == "http" || scheme == "https" || scheme == "file" || scheme == "channel" || scheme == "git" || scheme == "s3" || scheme == "ssh"; } diff --git a/src/libstore/filetransfer.hh b/src/libstore/filetransfer.hh index 3e61b23b1..ca61e3937 100644 --- a/src/libstore/filetransfer.hh +++ b/src/libstore/filetransfer.hh @@ -119,17 +119,17 @@ class FileTransferError : public Error { public: FileTransfer::Error error; - std::optional response; // intentionally optional + std::optional response; // intentionally optional template - FileTransferError(FileTransfer::Error error, std::optional response, const Args & ... args); + FileTransferError(FileTransfer::Error error, std::optional response, const Args & ... args); virtual const char* sname() const override { return "FileTransferError"; } }; -bool isUri(const string & s); +bool isUri(std::string_view s); /* Resolve deprecated 'channel:' URLs. */ -std::string resolveUri(const std::string & uri); +std::string resolveUri(std::string_view uri); } diff --git a/src/libstore/gc.cc b/src/libstore/gc.cc index e35199b3d..fd38b731c 100644 --- a/src/libstore/gc.cc +++ b/src/libstore/gc.cc @@ -47,9 +47,8 @@ static void makeSymlink(const Path & link, const Path & target) void LocalStore::addIndirectRoot(const Path & path) { - string hash = hashString(htSHA1, path).to_string(Base32, false); - Path realRoot = canonPath((format("%1%/%2%/auto/%3%") - % stateDir % gcRootsDir % hash).str()); + std::string hash = hashString(htSHA1, path).to_string(Base32, false); + Path realRoot = canonPath(fmt("%1%/%2%/auto/%3%", stateDir, gcRootsDir, hash)); makeSymlink(realRoot, path); } @@ -162,7 +161,7 @@ void LocalStore::addTempRoot(const StorePath & path) } /* Append the store path to the temporary roots file. */ - string s = printStorePath(path) + '\0'; + auto s = printStorePath(path) + '\0'; writeFull(state->fdTempRoots.get(), s); } @@ -203,12 +202,12 @@ void LocalStore::findTempRoots(Roots & tempRoots, bool censor) } /* Read the entire file. */ - string contents = readFile(fd.get()); + auto contents = readFile(fd.get()); /* Extract the roots. */ - string::size_type pos = 0, end; + std::string::size_type pos = 0, end; - while ((end = contents.find((char) 0, pos)) != string::npos) { + while ((end = contents.find((char) 0, pos)) != std::string::npos) { Path root(contents, pos, end - pos); debug("got temporary root '%s'", root); tempRoots[parseStorePath(root)].emplace(censor ? censored : fmt("{temp:%d}", pid)); @@ -305,7 +304,7 @@ Roots LocalStore::findRoots(bool censor) typedef std::unordered_map> UncheckedRoots; -static void readProcLink(const string & file, UncheckedRoots & roots) +static void readProcLink(const std::string & file, UncheckedRoots & roots) { /* 64 is the starting buffer size gnu readlink uses... */ auto bufsiz = ssize_t{64}; @@ -328,7 +327,7 @@ try_again: .emplace(file); } -static string quoteRegexChars(const string & raw) +static std::string quoteRegexChars(const std::string & raw) { static auto specialRegex = std::regex(R"([.^$\\*+?()\[\]{}|])"); return std::regex_replace(raw, specialRegex, R"(\$&)"); @@ -383,7 +382,7 @@ void LocalStore::findRuntimeRoots(Roots & roots, bool censor) try { auto mapFile = fmt("/proc/%s/maps", ent->d_name); - auto mapLines = tokenizeString>(readFile(mapFile), "\n"); + auto mapLines = tokenizeString>(readFile(mapFile), "\n"); for (const auto & line : mapLines) { auto match = std::smatch{}; if (std::regex_match(line, match, mapRegex)) @@ -784,7 +783,7 @@ void LocalStore::collectGarbage(const GCOptions & options, GCResults & results) struct dirent * dirent; while (errno = 0, dirent = readdir(dir.get())) { checkInterrupt(); - string name = dirent->d_name; + std::string name = dirent->d_name; if (name == "." || name == ".." || name == linksName) continue; if (auto storePath = maybeParseStorePath(storeDir + "/" + name)) @@ -825,7 +824,7 @@ void LocalStore::collectGarbage(const GCOptions & options, GCResults & results) struct dirent * dirent; while (errno = 0, dirent = readdir(dir.get())) { checkInterrupt(); - string name = dirent->d_name; + std::string name = dirent->d_name; if (name == "." || name == "..") continue; Path path = linksDir + "/" + name; diff --git a/src/libstore/globals.cc b/src/libstore/globals.cc index 81ca9cc0f..cc009a026 100644 --- a/src/libstore/globals.cc +++ b/src/libstore/globals.cc @@ -100,7 +100,7 @@ std::vector getUserConfigFiles() // Use the paths specified in NIX_USER_CONF_FILES if it has been defined auto nixConfFiles = getEnv("NIX_USER_CONF_FILES"); if (nixConfFiles.has_value()) { - return tokenizeString>(nixConfFiles.value(), ":"); + return tokenizeString>(nixConfFiles.value(), ":"); } // Use the paths specified by the XDG spec @@ -181,7 +181,7 @@ bool Settings::isWSL1() return hasSuffix(utsbuf.release, "-Microsoft"); } -const string nixVersion = PACKAGE_VERSION; +const std::string nixVersion = PACKAGE_VERSION; NLOHMANN_JSON_SERIALIZE_ENUM(SandboxMode, { {SandboxMode::smEnabled, true}, diff --git a/src/libstore/globals.hh b/src/libstore/globals.hh index 4a78729e9..b31a2e8dc 100644 --- a/src/libstore/globals.hh +++ b/src/libstore/globals.hh @@ -988,6 +988,6 @@ void loadConfFile(); // Used by the Settings constructor std::vector getUserConfigFiles(); -extern const string nixVersion; +extern const std::string nixVersion; } diff --git a/src/libstore/legacy-ssh-store.cc b/src/libstore/legacy-ssh-store.cc index f8b2662af..6b3daae7f 100644 --- a/src/libstore/legacy-ssh-store.cc +++ b/src/libstore/legacy-ssh-store.cc @@ -48,7 +48,7 @@ struct LegacySSHStore : public virtual LegacySSHStoreConfig, public virtual Stor static std::set uriSchemes() { return {"ssh"}; } - LegacySSHStore(const string & scheme, const string & host, const Params & params) + LegacySSHStore(const std::string & scheme, const std::string & host, const Params & params) : StoreConfig(params) , LegacySSHStoreConfig(params) , Store(params) @@ -107,7 +107,7 @@ struct LegacySSHStore : public virtual LegacySSHStoreConfig, public virtual Stor return conn; }; - string getUri() override + std::string getUri() override { return *uriSchemes().begin() + "://" + host; } @@ -225,13 +225,21 @@ struct LegacySSHStore : public virtual LegacySSHStoreConfig, public virtual Stor std::optional queryPathFromHashPart(const std::string & hashPart) override { unsupported("queryPathFromHashPart"); } - StorePath addToStore(const string & name, const Path & srcPath, - FileIngestionMethod method, HashType hashAlgo, - PathFilter & filter, RepairFlag repair, const StorePathSet & references) override + StorePath addToStore( + std::string_view name, + const Path & srcPath, + FileIngestionMethod method, + HashType hashAlgo, + PathFilter & filter, + RepairFlag repair, + const StorePathSet & references) override { unsupported("addToStore"); } - StorePath addTextToStore(const string & name, const string & s, - const StorePathSet & references, RepairFlag repair) override + StorePath addTextToStore( + std::string_view name, + std::string_view s, + const StorePathSet & references, + RepairFlag repair) override { unsupported("addTextToStore"); } private: diff --git a/src/libstore/local-fs-store.cc b/src/libstore/local-fs-store.cc index c933251db..c5ae7536f 100644 --- a/src/libstore/local-fs-store.cc +++ b/src/libstore/local-fs-store.cc @@ -85,7 +85,7 @@ void LocalFSStore::narFromPath(const StorePath & path, Sink & sink) dumpPath(getRealStoreDir() + std::string(printStorePath(path), storeDir.size()), sink); } -const string LocalFSStore::drvsLogDir = "drvs"; +const std::string LocalFSStore::drvsLogDir = "drvs"; std::optional LocalFSStore::getBuildLog(const StorePath & path_) { diff --git a/src/libstore/local-fs-store.hh b/src/libstore/local-fs-store.hh index e44b27cc2..d34f0cb62 100644 --- a/src/libstore/local-fs-store.hh +++ b/src/libstore/local-fs-store.hh @@ -27,7 +27,7 @@ class LocalFSStore : public virtual LocalFSStoreConfig, public virtual Store { public: - const static string drvsLogDir; + const static std::string drvsLogDir; LocalFSStore(const Params & params); diff --git a/src/libstore/local-store.cc b/src/libstore/local-store.cc index 1a02b916a..1ee71b1c0 100644 --- a/src/libstore/local-store.cc +++ b/src/libstore/local-store.cc @@ -70,7 +70,7 @@ int getSchema(Path schemaPath) { int curSchema = 0; if (pathExists(schemaPath)) { - string s = readFile(schemaPath); + auto s = readFile(schemaPath); auto n = string2Int(s); if (!n) throw Error("'%1%' is corrupt", schemaPath); @@ -239,7 +239,7 @@ LocalStore::LocalStore(const Params & params) res = posix_fallocate(fd.get(), 0, settings.reservedSize); #endif if (res == -1) { - writeFull(fd.get(), string(settings.reservedSize, 'X')); + writeFull(fd.get(), std::string(settings.reservedSize, 'X')); [[gnu::unused]] auto res2 = ftruncate(fd.get(), settings.reservedSize); } } @@ -450,7 +450,7 @@ void LocalStore::openDB(State & state, bool create) throw SysError("Nix database directory '%1%' is not writable", dbDir); /* Open the Nix database. */ - string dbPath = dbDir + "/db.sqlite"; + std::string dbPath = dbDir + "/db.sqlite"; auto & db(state.db); state.db = SQLite(dbPath, create); @@ -471,19 +471,19 @@ void LocalStore::openDB(State & state, bool create) should be safe enough. If the user asks for it, don't sync at all. This can cause database corruption if the system crashes. */ - string syncMode = settings.fsyncMetadata ? "normal" : "off"; + std::string syncMode = settings.fsyncMetadata ? "normal" : "off"; db.exec("pragma synchronous = " + syncMode); /* Set the SQLite journal mode. WAL mode is fastest, so it's the default. */ - string mode = settings.useSQLiteWAL ? "wal" : "truncate"; - string prevMode; + std::string mode = settings.useSQLiteWAL ? "wal" : "truncate"; + std::string prevMode; { SQLiteStmt stmt; stmt.create(db, "pragma main.journal_mode;"); if (sqlite3_step(stmt) != SQLITE_ROW) throwSQLiteError(db, "querying journal mode"); - prevMode = string((const char *) sqlite3_column_text(stmt, 0)); + prevMode = std::string((const char *) sqlite3_column_text(stmt, 0)); } if (prevMode != mode && sqlite3_exec(db, ("pragma main.journal_mode = " + mode + ";").c_str(), 0, 0, 0) != SQLITE_OK) @@ -679,7 +679,7 @@ void LocalStore::checkDerivationOutputs(const StorePath & drvPath, const Derivat { assert(drvPath.isDerivation()); std::string drvName(drvPath.name()); - drvName = string(drvName, 0, drvName.size() - drvExtension.size()); + drvName = drvName.substr(0, drvName.size() - drvExtension.size()); auto envHasRightPath = [&](const StorePath & actual, const std::string & varName) { @@ -786,7 +786,11 @@ void LocalStore::registerDrvOutput(const Realisation & info) }); } -void LocalStore::cacheDrvOutputMapping(State & state, const uint64_t deriver, const string & outputName, const StorePath & output) +void LocalStore::cacheDrvOutputMapping( + State & state, + const uint64_t deriver, + const std::string & outputName, + const StorePath & output) { retrySQLite([&]() { state.stmts->AddDerivationOutput.use() @@ -795,7 +799,6 @@ void LocalStore::cacheDrvOutputMapping(State & state, const uint64_t deriver, co (printStorePath(output)) .exec(); }); - } @@ -1436,7 +1439,9 @@ StorePath LocalStore::addToStoreFromDump(Source & source0, std::string_view name } -StorePath LocalStore::addTextToStore(const string & name, const string & s, +StorePath LocalStore::addTextToStore( + std::string_view name, + std::string_view s, const StorePathSet & references, RepairFlag repair) { auto hash = hashString(htSHA256, s); @@ -1548,7 +1553,7 @@ bool LocalStore::verifyStore(bool checkContents, RepairFlag repair) for (auto & link : readDirectory(linksDir)) { printMsg(lvlTalkative, "checking contents of '%s'", link.name); Path linkPath = linksDir + "/" + link.name; - string hash = hashPath(htSHA256, linkPath).first.to_string(Base32, false); + std::string hash = hashPath(htSHA256, linkPath).first.to_string(Base32, false); if (hash != link.name) { printError("link '%s' was modified! expected hash '%s', got '%s'", linkPath, link.name, hash); diff --git a/src/libstore/local-store.hh b/src/libstore/local-store.hh index a9c7475ac..1a278c9a8 100644 --- a/src/libstore/local-store.hh +++ b/src/libstore/local-store.hh @@ -147,8 +147,11 @@ public: StorePath addToStoreFromDump(Source & dump, std::string_view name, FileIngestionMethod method, HashType hashAlgo, RepairFlag repair, const StorePathSet & references) override; - StorePath addTextToStore(const string & name, const string & s, - const StorePathSet & references, RepairFlag repair) override; + StorePath addTextToStore( + std::string_view name, + std::string_view s, + const StorePathSet & references, + RepairFlag repair) override; void addTempRoot(const StorePath & path) override; @@ -204,7 +207,11 @@ public: derivation 'deriver'. */ void registerDrvOutput(const Realisation & info) override; void registerDrvOutput(const Realisation & info, CheckSigsFlag checkSigs) override; - void cacheDrvOutputMapping(State & state, const uint64_t deriver, const string & outputName, const StorePath & output); + void cacheDrvOutputMapping( + State & state, + const uint64_t deriver, + const std::string & outputName, + const StorePath & output); std::optional queryRealisation_(State & state, const DrvOutput & id); std::optional> queryRealisationCore_(State & state, const DrvOutput & id); diff --git a/src/libstore/lock.hh b/src/libstore/lock.hh index 8fbb67ddc..3d29a7b5b 100644 --- a/src/libstore/lock.hh +++ b/src/libstore/lock.hh @@ -13,7 +13,7 @@ private: AutoCloseFD fdUserLock; bool isEnabled = false; - string user; + std::string user; uid_t uid = 0; gid_t gid = 0; std::vector supplementaryGIDs; @@ -23,7 +23,7 @@ public: void kill(); - string getUser() { return user; } + std::string getUser() { return user; } uid_t getUID() { assert(uid); return uid; } uid_t getGID() { assert(gid); return gid; } std::vector getSupplementaryGIDs() { return supplementaryGIDs; } diff --git a/src/libstore/machines.cc b/src/libstore/machines.cc index b6270a81b..e87f46980 100644 --- a/src/libstore/machines.cc +++ b/src/libstore/machines.cc @@ -39,19 +39,19 @@ Machine::Machine(decltype(storeUri) storeUri, sshPublicHostKey(sshPublicHostKey) {} -bool Machine::allSupported(const std::set & features) const +bool Machine::allSupported(const std::set & features) const { return std::all_of(features.begin(), features.end(), - [&](const string & feature) { + [&](const std::string & feature) { return supportedFeatures.count(feature) || mandatoryFeatures.count(feature); }); } -bool Machine::mandatoryMet(const std::set & features) const +bool Machine::mandatoryMet(const std::set & features) const { return std::all_of(mandatoryFeatures.begin(), mandatoryFeatures.end(), - [&](const string & feature) { + [&](const std::string & feature) { return features.count(feature); }); } @@ -89,7 +89,7 @@ ref Machine::openStore() const static std::vector expandBuilderLines(const std::string & builders) { std::vector result; - for (auto line : tokenizeString>(builders, "\n;")) { + for (auto line : tokenizeString>(builders, "\n;")) { trim(line); line.erase(std::find(line.begin(), line.end(), '#'), line.end()); if (line.empty()) continue; @@ -117,7 +117,7 @@ static std::vector expandBuilderLines(const std::string & builders) static Machine parseBuilderLine(const std::string & line) { - const auto tokens = tokenizeString>(line); + const auto tokens = tokenizeString>(line); auto isSet = [&](size_t fieldIndex) { return tokens.size() > fieldIndex && tokens[fieldIndex] != "" && tokens[fieldIndex] != "-"; @@ -146,17 +146,18 @@ static Machine parseBuilderLine(const std::string & line) return { tokens[0], - isSet(1) ? tokenizeString>(tokens[1], ",") : std::vector{settings.thisSystem}, + isSet(1) ? tokenizeString>(tokens[1], ",") : std::vector{settings.thisSystem}, isSet(2) ? tokens[2] : "", isSet(3) ? parseUnsignedIntField(3) : 1U, isSet(4) ? parseUnsignedIntField(4) : 1U, - isSet(5) ? tokenizeString>(tokens[5], ",") : std::set{}, - isSet(6) ? tokenizeString>(tokens[6], ",") : std::set{}, + isSet(5) ? tokenizeString>(tokens[5], ",") : std::set{}, + isSet(6) ? tokenizeString>(tokens[6], ",") : std::set{}, isSet(7) ? ensureBase64(7) : "" }; } -static Machines parseBuilderLines(const std::vector& builders) { +static Machines parseBuilderLines(const std::vector & builders) +{ Machines result; std::transform(builders.begin(), builders.end(), std::back_inserter(result), parseBuilderLine); return result; diff --git a/src/libstore/nar-accessor.cc b/src/libstore/nar-accessor.cc index 7d27d7667..72d41cc94 100644 --- a/src/libstore/nar-accessor.cc +++ b/src/libstore/nar-accessor.cc @@ -90,7 +90,7 @@ struct NarAccessor : public FSAccessor void receiveContents(std::string_view data) override { } - void createSymlink(const Path & path, const string & target) override + void createSymlink(const Path & path, const std::string & target) override { createMember(path, NarMember{FSAccessor::Type::tSymlink, false, 0, 0, target}); diff --git a/src/libstore/nar-info.cc b/src/libstore/nar-info.cc index 49079388a..2d75e7a82 100644 --- a/src/libstore/nar-info.cc +++ b/src/libstore/nar-info.cc @@ -11,7 +11,7 @@ NarInfo::NarInfo(const Store & store, const std::string & s, const std::string & return Error("NAR info file '%1%' is corrupt", whence); }; - auto parseHashField = [&](const string & s) { + auto parseHashField = [&](const std::string & s) { try { return Hash::parseAnyPrefixed(s); } catch (BadHash &) { diff --git a/src/libstore/optimise-store.cc b/src/libstore/optimise-store.cc index 13cb142f8..8af9b1dde 100644 --- a/src/libstore/optimise-store.cc +++ b/src/libstore/optimise-store.cc @@ -77,7 +77,7 @@ Strings LocalStore::readDirectoryIgnoringInodes(const Path & path, const InodeHa continue; } - string name = dirent->d_name; + std::string name = dirent->d_name; if (name == "." || name == "..") continue; names.push_back(name); } diff --git a/src/libstore/path-with-outputs.cc b/src/libstore/path-with-outputs.cc index e5a121e00..97aa01b57 100644 --- a/src/libstore/path-with-outputs.cc +++ b/src/libstore/path-with-outputs.cc @@ -49,9 +49,9 @@ std::pair parsePathWithOutputs(std::string_view s) { size_t n = s.find("!"); return n == s.npos - ? std::make_pair(s, std::set()) + ? std::make_pair(s, std::set()) : std::make_pair(((std::string_view) s).substr(0, n), - tokenizeString>(((std::string_view) s).substr(n + 1), ",")); + tokenizeString>(((std::string_view) s).substr(n + 1), ",")); } diff --git a/src/libstore/path.hh b/src/libstore/path.hh index 06ba0663b..e65fee622 100644 --- a/src/libstore/path.hh +++ b/src/libstore/path.hh @@ -62,7 +62,7 @@ public: typedef std::set StorePathSet; typedef std::vector StorePaths; -typedef std::map OutputPathMap; +typedef std::map OutputPathMap; typedef std::map> StorePathCAMap; diff --git a/src/libstore/pathlocks.cc b/src/libstore/pathlocks.cc index 2da74e262..42023cd0a 100644 --- a/src/libstore/pathlocks.cc +++ b/src/libstore/pathlocks.cc @@ -74,7 +74,7 @@ PathLocks::PathLocks() } -PathLocks::PathLocks(const PathSet & paths, const string & waitMsg) +PathLocks::PathLocks(const PathSet & paths, const std::string & waitMsg) : deletePaths(false) { lockPaths(paths, waitMsg); @@ -82,7 +82,7 @@ PathLocks::PathLocks(const PathSet & paths, const string & waitMsg) bool PathLocks::lockPaths(const PathSet & paths, - const string & waitMsg, bool wait) + const std::string & waitMsg, bool wait) { assert(fds.empty()); diff --git a/src/libstore/pathlocks.hh b/src/libstore/pathlocks.hh index 759b9a584..5e3a734b4 100644 --- a/src/libstore/pathlocks.hh +++ b/src/libstore/pathlocks.hh @@ -26,9 +26,9 @@ private: public: PathLocks(); PathLocks(const PathSet & paths, - const string & waitMsg = ""); + const std::string & waitMsg = ""); bool lockPaths(const PathSet & _paths, - const string & waitMsg = "", + const std::string & waitMsg = "", bool wait = true); ~PathLocks(); void unlock(); diff --git a/src/libstore/profiles.cc b/src/libstore/profiles.cc index 73163424c..3e4188188 100644 --- a/src/libstore/profiles.cc +++ b/src/libstore/profiles.cc @@ -15,12 +15,12 @@ namespace nix { /* Parse a generation name of the format `--link'. */ -static std::optional parseName(const string & profileName, const string & name) +static std::optional parseName(const std::string & profileName, const std::string & name) { - if (string(name, 0, profileName.size() + 1) != profileName + "-") return {}; - string s = string(name, profileName.size() + 1); - string::size_type p = s.find("-link"); - if (p == string::npos) return {}; + if (name.substr(0, profileName.size() + 1) != profileName + "-") return {}; + auto s = name.substr(profileName.size() + 1); + auto p = s.find("-link"); + if (p == std::string::npos) return {}; if (auto n = string2Int(s.substr(0, p))) return *n; else @@ -209,13 +209,13 @@ void deleteGenerationsOlderThan(const Path & profile, time_t t, bool dryRun) } -void deleteGenerationsOlderThan(const Path & profile, const string & timeSpec, bool dryRun) +void deleteGenerationsOlderThan(const Path & profile, std::string_view timeSpec, bool dryRun) { if (timeSpec.empty() || timeSpec[timeSpec.size() - 1] != 'd') throw UsageError("invalid number of days specifier '%1%', expected something like '14d'", timeSpec); time_t curTime = time(0); - string strDays = string(timeSpec, 0, timeSpec.size() - 1); + auto strDays = timeSpec.substr(0, timeSpec.size() - 1); auto days = string2Int(strDays); if (!days || *days < 1) @@ -274,7 +274,7 @@ void lockProfile(PathLocks & lock, const Path & profile) } -string optimisticLockProfile(const Path & profile) +std::string optimisticLockProfile(const Path & profile) { return pathExists(profile) ? readLink(profile) : ""; } diff --git a/src/libstore/profiles.hh b/src/libstore/profiles.hh index d100c970c..408ca039c 100644 --- a/src/libstore/profiles.hh +++ b/src/libstore/profiles.hh @@ -42,7 +42,7 @@ void deleteOldGenerations(const Path & profile, bool dryRun); void deleteGenerationsOlderThan(const Path & profile, time_t t, bool dryRun); -void deleteGenerationsOlderThan(const Path & profile, const string & timeSpec, bool dryRun); +void deleteGenerationsOlderThan(const Path & profile, std::string_view timeSpec, bool dryRun); void switchLink(Path link, Path target); @@ -66,7 +66,7 @@ void lockProfile(PathLocks & lock, const Path & profile); generally cheap, since the build results are still in the Nix store. Most of the time, only the user environment has to be rebuilt. */ -string optimisticLockProfile(const Path & profile); +std::string optimisticLockProfile(const Path & profile); /* Resolve ~/.nix-profile. If ~/.nix-profile doesn't exist yet, create it. */ diff --git a/src/libstore/references.cc b/src/libstore/references.cc index 91b3fc142..34dce092c 100644 --- a/src/libstore/references.cc +++ b/src/libstore/references.cc @@ -68,7 +68,7 @@ void RefScanSink::operator () (std::string_view data) std::pair scanForReferences( - const string & path, + const std::string & path, const StorePathSet & refs) { HashSink hashSink { htSHA256 }; @@ -121,7 +121,7 @@ void RewritingSink::operator () (std::string_view data) s.append(data); size_t j = 0; - while ((j = s.find(from, j)) != string::npos) { + while ((j = s.find(from, j)) != std::string::npos) { matches.push_back(pos + j); s.replace(j, from.size(), to); } diff --git a/src/libstore/remote-store.cc b/src/libstore/remote-store.cc index c6f083dea..e7ffa6595 100644 --- a/src/libstore/remote-store.cc +++ b/src/libstore/remote-store.cc @@ -661,8 +661,11 @@ void RemoteStore::addMultipleToStore( } -StorePath RemoteStore::addTextToStore(const string & name, const string & s, - const StorePathSet & references, RepairFlag repair) +StorePath RemoteStore::addTextToStore( + std::string_view name, + std::string_view s, + const StorePathSet & references, + RepairFlag repair) { StringSource source(s); return addCAToStore(source, name, TextHashMethod{}, references, repair)->path; @@ -1000,7 +1003,7 @@ std::exception_ptr RemoteStore::Connection::processStderr(Sink * sink, Source * auto msg = readNum(from); if (msg == STDERR_WRITE) { - string s = readString(from); + auto s = readString(from); if (!sink) throw Error("no sink"); (*sink)(s); } @@ -1017,7 +1020,7 @@ std::exception_ptr RemoteStore::Connection::processStderr(Sink * sink, Source * if (GET_PROTOCOL_MINOR(daemonVersion) >= 26) { return std::make_exception_ptr(readError(from)); } else { - string error = readString(from); + auto error = readString(from); unsigned int status = readInt(from); return std::make_exception_ptr(Error(status, error)); } diff --git a/src/libstore/remote-store.hh b/src/libstore/remote-store.hh index 55cfd5cc6..b94216d31 100644 --- a/src/libstore/remote-store.hh +++ b/src/libstore/remote-store.hh @@ -83,8 +83,11 @@ public: RepairFlag repair, CheckSigsFlag checkSigs) override; - StorePath addTextToStore(const string & name, const string & s, - const StorePathSet & references, RepairFlag repair) override; + StorePath addTextToStore( + std::string_view name, + std::string_view s, + const StorePathSet & references, + RepairFlag repair) override; void registerDrvOutput(const Realisation & info) override; diff --git a/src/libstore/s3-binary-cache-store.cc b/src/libstore/s3-binary-cache-store.cc index a024e971d..844553ad3 100644 --- a/src/libstore/s3-binary-cache-store.cc +++ b/src/libstore/s3-binary-cache-store.cc @@ -87,7 +87,11 @@ static void initAWS() }); } -S3Helper::S3Helper(const string & profile, const string & region, const string & scheme, const string & endpoint) +S3Helper::S3Helper( + const std::string & profile, + const std::string & region, + const std::string & scheme, + const std::string & endpoint) : config(makeConfig(region, scheme, endpoint)) , client(make_ref( profile == "" @@ -121,7 +125,10 @@ class RetryStrategy : public Aws::Client::DefaultRetryStrategy } }; -ref S3Helper::makeConfig(const string & region, const string & scheme, const string & endpoint) +ref S3Helper::makeConfig( + const std::string & region, + const std::string & scheme, + const std::string & endpoint) { initAWS(); auto res = make_ref(); diff --git a/src/libstore/sqlite.cc b/src/libstore/sqlite.cc index 1d6baf02d..e6ecadd7f 100644 --- a/src/libstore/sqlite.cc +++ b/src/libstore/sqlite.cc @@ -71,7 +71,7 @@ uint64_t SQLite::getLastInsertedRowId() return sqlite3_last_insert_rowid(db); } -void SQLiteStmt::create(sqlite3 * db, const string & sql) +void SQLiteStmt::create(sqlite3 * db, const std::string & sql) { checkInterrupt(); assert(!stmt); diff --git a/src/libstore/ssh.cc b/src/libstore/ssh.cc index 93f72675d..1bbad71f2 100644 --- a/src/libstore/ssh.cc +++ b/src/libstore/ssh.cc @@ -29,7 +29,7 @@ void SSHMaster::addCommonSSHOpts(Strings & args) if (!sshPublicHostKey.empty()) { Path fileName = (Path) *state->tmpDir + "/host-key"; auto p = host.rfind("@"); - string thost = p != string::npos ? string(host, p + 1) : host; + std::string thost = p != std::string::npos ? std::string(host, p + 1) : host; writeFile(fileName, thost + " " + base64Decode(sshPublicHostKey) + "\n"); args.insert(args.end(), {"-oUserKnownHostsFile=" + fileName}); } diff --git a/src/libstore/store-api.cc b/src/libstore/store-api.cc index 8fcdc8b57..86fa6a211 100644 --- a/src/libstore/store-api.cc +++ b/src/libstore/store-api.cc @@ -39,7 +39,7 @@ Path Store::followLinksToStore(std::string_view _path) const Path path = absPath(std::string(_path)); while (!isInStore(path)) { if (!isLink(path)) break; - string target = readLink(path); + auto target = readLink(path); path = absPath(target, dirOf(path)); } if (!isInStore(path)) @@ -138,8 +138,8 @@ StorePath Store::makeStorePath(std::string_view type, std::string_view hash, std::string_view name) const { /* e.g., "source:sha256:1abc...:/nix/store:foo.tar.gz" */ - string s = std::string { type } + ":" + std::string { hash } - + ":" + storeDir + ":" + std::string { name }; + auto s = std::string(type) + ":" + std::string(hash) + + ":" + storeDir + ":" + std::string(name); auto h = compressHash(hashString(htSHA256, s), 20); return StorePath(h, name); } @@ -161,7 +161,7 @@ StorePath Store::makeOutputPath(std::string_view id, static std::string makeType( const Store & store, - string && type, + std::string && type, const StorePathSet & references, bool hasSelfReference = false) { @@ -229,15 +229,23 @@ std::pair Store::computeStorePathForPath(std::string_view name, } -StorePath Store::computeStorePathForText(const string & name, const string & s, +StorePath Store::computeStorePathForText( + std::string_view name, + std::string_view s, const StorePathSet & references) const { return makeTextPath(name, hashString(htSHA256, s), references); } -StorePath Store::addToStore(const string & name, const Path & _srcPath, - FileIngestionMethod method, HashType hashAlgo, PathFilter & filter, RepairFlag repair, const StorePathSet & references) +StorePath Store::addToStore( + std::string_view name, + const Path & _srcPath, + FileIngestionMethod method, + HashType hashAlgo, + PathFilter & filter, + RepairFlag repair, + const StorePathSet & references) { Path srcPath(absPath(_srcPath)); auto source = sinkToSource([&](Sink & sink) { @@ -688,10 +696,10 @@ StorePathSet Store::queryValidPaths(const StorePathSet & paths, SubstituteFlag m /* Return a string accepted by decodeValidPathInfo() that registers the specified paths as valid. Note: it's the responsibility of the caller to provide a closure. */ -string Store::makeValidityRegistration(const StorePathSet & paths, +std::string Store::makeValidityRegistration(const StorePathSet & paths, bool showDerivers, bool showHash) { - string s = ""; + std::string s = ""; for (auto & i : paths) { s += printStorePath(i) + "\n"; @@ -1131,7 +1139,7 @@ std::optional decodeValidPathInfo(const Store & store, std::istre getline(str, path); if (str.eof()) { return {}; } if (!hashGiven) { - string s; + std::string s; getline(str, s); auto narHash = Hash::parseAny(s, htSHA256); getline(str, s); @@ -1144,7 +1152,7 @@ std::optional decodeValidPathInfo(const Store & store, std::istre std::string deriver; getline(str, deriver); if (deriver != "") info.deriver = store.parseStorePath(deriver); - string s; + std::string s; getline(str, s); auto n = string2Int(s); if (!n) throw Error("number expected"); @@ -1168,7 +1176,7 @@ std::string Store::showPaths(const StorePathSet & paths) } -string showPaths(const PathSet & paths) +std::string showPaths(const PathSet & paths) { return concatStringsSep(", ", quoteStrings(paths)); } diff --git a/src/libstore/store-api.hh b/src/libstore/store-api.hh index 90d2e93ed..e4fb1f1fd 100644 --- a/src/libstore/store-api.hh +++ b/src/libstore/store-api.hh @@ -352,7 +352,9 @@ public: simply yield a different store path, so other users wouldn't be affected), but it has some backwards compatibility issues (the hashing scheme changes), so I'm not doing that for now. */ - StorePath computeStorePathForText(const string & name, const string & s, + StorePath computeStorePathForText( + std::string_view name, + std::string_view s, const StorePathSet & references) const; /* Check whether a path is valid. */ @@ -482,9 +484,14 @@ public: validity the resulting path. The resulting path is returned. The function object `filter' can be used to exclude files (see libutil/archive.hh). */ - virtual StorePath addToStore(const string & name, const Path & srcPath, - FileIngestionMethod method = FileIngestionMethod::Recursive, HashType hashAlgo = htSHA256, - PathFilter & filter = defaultPathFilter, RepairFlag repair = NoRepair, const StorePathSet & references = StorePathSet()); + virtual StorePath addToStore( + std::string_view name, + const Path & srcPath, + FileIngestionMethod method = FileIngestionMethod::Recursive, + HashType hashAlgo = htSHA256, + PathFilter & filter = defaultPathFilter, + RepairFlag repair = NoRepair, + const StorePathSet & references = StorePathSet()); /* Copy the contents of a path to the store and register the validity the resulting path, using a constant amount of @@ -506,8 +513,11 @@ public: /* Like addToStore, but the contents written to the output path is a regular file containing the given string. */ - virtual StorePath addTextToStore(const string & name, const string & s, - const StorePathSet & references, RepairFlag repair = NoRepair) = 0; + virtual StorePath addTextToStore( + std::string_view name, + std::string_view s, + const StorePathSet & references, + RepairFlag repair = NoRepair) = 0; /** * Add a mapping indicating that `deriver!outputName` maps to the output path @@ -608,7 +618,7 @@ public: /* Return a string representing information about the path that can be loaded into the database using `nix-store --load-db' or `nix-store --register-validity'. */ - string makeValidityRegistration(const StorePathSet & paths, + std::string makeValidityRegistration(const StorePathSet & paths, bool showDerivers, bool showHash); /* Write a JSON representation of store path metadata, such as the @@ -910,7 +920,7 @@ struct RegisterStoreImplementation /* Display a set of paths in human-readable form (i.e., between quotes and separated by commas). */ -string showPaths(const PathSet & paths); +std::string showPaths(const PathSet & paths); std::optional decodeValidPathInfo( diff --git a/src/libutil/archive.cc b/src/libutil/archive.cc index fdee643b1..eda004756 100644 --- a/src/libutil/archive.cc +++ b/src/libutil/archive.cc @@ -37,7 +37,7 @@ static GlobalConfig::Register rArchiveSettings(&archiveSettings); const std::string narVersionMagic1 = "nix-archive-1"; -static string caseHackSuffix = "~nix~case~hack~"; +static std::string caseHackSuffix = "~nix~case~hack~"; PathFilter defaultPathFilter = [](const Path &) { return true; }; @@ -84,12 +84,12 @@ static void dump(const Path & path, Sink & sink, PathFilter & filter) /* If we're on a case-insensitive system like macOS, undo the case hack applied by restorePath(). */ - std::map unhacked; + std::map unhacked; for (auto & i : readDirectory(path)) if (archiveSettings.useCaseHack) { - string name(i.name); + std::string name(i.name); size_t pos = i.name.find(caseHackSuffix); - if (pos != string::npos) { + if (pos != std::string::npos) { debug(format("removing case hack suffix from '%1%'") % (path + "/" + i.name)); name.erase(pos); } @@ -124,13 +124,13 @@ void dumpPath(const Path & path, Sink & sink, PathFilter & filter) } -void dumpString(const std::string & s, Sink & sink) +void dumpString(std::string_view s, Sink & sink) { sink << narVersionMagic1 << "(" << "type" << "regular" << "contents" << s << ")"; } -static SerialisationError badArchive(string s) +static SerialisationError badArchive(const std::string & s) { return SerialisationError("bad archive: " + s); } @@ -171,7 +171,7 @@ static void parseContents(ParseSink & sink, Source & source, const Path & path) struct CaseInsensitiveCompare { - bool operator() (const string & a, const string & b) const + bool operator() (const std::string & a, const std::string & b) const { return strcasecmp(a.c_str(), b.c_str()) < 0; } @@ -180,7 +180,7 @@ struct CaseInsensitiveCompare static void parse(ParseSink & sink, Source & source, const Path & path) { - string s; + std::string s; s = readString(source); if (s != "(") throw badArchive("expected open tag"); @@ -201,7 +201,7 @@ static void parse(ParseSink & sink, Source & source, const Path & path) else if (s == "type") { if (type != tpUnknown) throw badArchive("multiple type fields"); - string t = readString(source); + std::string t = readString(source); if (t == "regular") { type = tpRegular; @@ -232,7 +232,7 @@ static void parse(ParseSink & sink, Source & source, const Path & path) } else if (s == "entry" && type == tpDirectory) { - string name, prevName; + std::string name, prevName; s = readString(source); if (s != "(") throw badArchive("expected open tag"); @@ -246,7 +246,7 @@ static void parse(ParseSink & sink, Source & source, const Path & path) break; } else if (s == "name") { name = readString(source); - if (name.empty() || name == "." || name == ".." || name.find('/') != string::npos || name.find((char) 0) != string::npos) + if (name.empty() || name == "." || name == ".." || name.find('/') != std::string::npos || name.find((char) 0) != std::string::npos) throw Error("NAR contains invalid file name '%1%'", name); if (name <= prevName) throw Error("NAR directory is not sorted"); @@ -269,7 +269,7 @@ static void parse(ParseSink & sink, Source & source, const Path & path) } else if (s == "target" && type == tpSymlink) { - string target = readString(source); + std::string target = readString(source); sink.createSymlink(path, target); } @@ -281,7 +281,7 @@ static void parse(ParseSink & sink, Source & source, const Path & path) void parseDump(ParseSink & sink, Source & source) { - string version; + std::string version; try { version = readString(source, narVersionMagic1.size()); } catch (SerialisationError & e) { @@ -345,7 +345,7 @@ struct RestoreSink : ParseSink writeFull(fd.get(), data); } - void createSymlink(const Path & path, const string & target) override + void createSymlink(const Path & path, const std::string & target) override { Path p = dstPath + path; nix::createSymlink(target, p); diff --git a/src/libutil/archive.hh b/src/libutil/archive.hh index 9e9e11b1a..fca351605 100644 --- a/src/libutil/archive.hh +++ b/src/libutil/archive.hh @@ -48,7 +48,7 @@ namespace nix { void dumpPath(const Path & path, Sink & sink, PathFilter & filter = defaultPathFilter); -void dumpString(const std::string & s, Sink & sink); +void dumpString(std::string_view s, Sink & sink); /* FIXME: fix this API, it sucks. */ struct ParseSink @@ -60,7 +60,7 @@ struct ParseSink virtual void preallocateContents(uint64_t size) { }; virtual void receiveContents(std::string_view data) { }; - virtual void createSymlink(const Path & path, const string & target) { }; + virtual void createSymlink(const Path & path, const std::string & target) { }; }; /* If the NAR archive contains a single file at top-level, then save @@ -82,7 +82,7 @@ struct RetrieveRegularNARSink : ParseSink sink(data); } - void createSymlink(const Path & path, const string & target) override + void createSymlink(const Path & path, const std::string & target) override { regular = false; } diff --git a/src/libutil/args.cc b/src/libutil/args.cc index a739d6b4e..f970c0e9e 100644 --- a/src/libutil/args.cc +++ b/src/libutil/args.cc @@ -76,13 +76,13 @@ void Args::parseCmdline(const Strings & _cmdline) /* Expand compound dash options (i.e., `-qlf' -> `-q -l -f', `-j3` -> `-j 3`). */ if (!dashDash && arg.length() > 2 && arg[0] == '-' && arg[1] != '-' && isalpha(arg[1])) { - *pos = (string) "-" + arg[1]; + *pos = (std::string) "-" + arg[1]; auto next = pos; ++next; for (unsigned int j = 2; j < arg.length(); j++) if (isalpha(arg[j])) - cmdline.insert(next, (string) "-" + arg[j]); + cmdline.insert(next, (std::string) "-" + arg[j]); else { - cmdline.insert(next, string(arg, j)); + cmdline.insert(next, std::string(arg, j)); break; } arg = *pos; @@ -139,7 +139,7 @@ bool Args::processFlag(Strings::iterator & pos, Strings::iterator end) return true; }; - if (string(*pos, 0, 2) == "--") { + if (std::string(*pos, 0, 2) == "--") { if (auto prefix = needsCompletion(*pos)) { for (auto & [name, flag] : longFlags) { if (!hiddenCategories.count(flag->category) @@ -147,12 +147,12 @@ bool Args::processFlag(Strings::iterator & pos, Strings::iterator end) completions->add("--" + name, flag->description); } } - auto i = longFlags.find(string(*pos, 2)); + auto i = longFlags.find(std::string(*pos, 2)); if (i == longFlags.end()) return false; return process("--" + i->first, *i->second); } - if (string(*pos, 0, 1) == "-" && pos->size() == 2) { + if (std::string(*pos, 0, 1) == "-" && pos->size() == 2) { auto c = (*pos)[1]; auto i = shortFlags.find(c); if (i == shortFlags.end()) return false; diff --git a/src/libutil/args.hh b/src/libutil/args.hh index 76b1cfe92..fdd036f9a 100644 --- a/src/libutil/args.hh +++ b/src/libutil/args.hh @@ -158,7 +158,7 @@ public: } /* Expect a string argument. */ - void expectArg(const std::string & label, string * dest, bool optional = false) + void expectArg(const std::string & label, std::string * dest, bool optional = false) { expectArgs({ .label = label, diff --git a/src/libutil/config.cc b/src/libutil/config.cc index 8e05f1765..9bb412b4f 100644 --- a/src/libutil/config.cc +++ b/src/libutil/config.cc @@ -81,16 +81,16 @@ void AbstractConfig::applyConfig(const std::string & contents, const std::string unsigned int pos = 0; while (pos < contents.size()) { - string line; + std::string line; while (pos < contents.size() && contents[pos] != '\n') line += contents[pos++]; pos++; - string::size_type hash = line.find('#'); - if (hash != string::npos) - line = string(line, 0, hash); + auto hash = line.find('#'); + if (hash != std::string::npos) + line = std::string(line, 0, hash); - auto tokens = tokenizeString>(line); + auto tokens = tokenizeString>(line); if (tokens.empty()) continue; if (tokens.size() < 2) @@ -120,7 +120,7 @@ void AbstractConfig::applyConfig(const std::string & contents, const std::string if (tokens[1] != "=") throw UsageError("illegal configuration line '%1%' in '%2%'", line, path); - string name = tokens[0]; + std::string name = tokens[0]; auto i = tokens.begin(); advance(i, 2); @@ -132,7 +132,7 @@ void AbstractConfig::applyConfig(const std::string & contents, const std::string void AbstractConfig::applyConfigFile(const Path & path) { try { - string contents = readFile(path); + std::string contents = readFile(path); applyConfig(contents, path); } catch (SysError &) { } } diff --git a/src/libutil/error.cc b/src/libutil/error.cc index dd9678ee7..dcd2f82a5 100644 --- a/src/libutil/error.cc +++ b/src/libutil/error.cc @@ -17,7 +17,7 @@ BaseError & BaseError::addTrace(std::optional e, hintformat hint) // c++ std::exception descendants must have a 'const char* what()' function. // This stringifies the error and caches it for use by what(), or similarly by msg(). -const string & BaseError::calcWhat() const +const std::string & BaseError::calcWhat() const { if (what_.has_value()) return *what_; @@ -32,14 +32,14 @@ const string & BaseError::calcWhat() const } } -std::optional ErrorInfo::programName = std::nullopt; +std::optional ErrorInfo::programName = std::nullopt; std::ostream & operator<<(std::ostream & os, const hintformat & hf) { return os << hf.str(); } -string showErrPos(const ErrPos & errPos) +std::string showErrPos(const ErrPos & errPos) { if (errPos.line > 0) { if (errPos.column > 0) { @@ -68,7 +68,7 @@ std::optional getCodeLines(const ErrPos & errPos) // count the newlines. int count = 0; - string line; + std::string line; int pl = errPos.line - 1; do { @@ -100,7 +100,7 @@ std::optional getCodeLines(const ErrPos & errPos) std::istringstream iss(errPos.file); // count the newlines. int count = 0; - string line; + std::string line; int pl = errPos.line - 1; LinesOfCode loc; @@ -132,7 +132,7 @@ std::optional getCodeLines(const ErrPos & errPos) // print lines of code to the ostream, indicating the error column. void printCodeLines(std::ostream & out, - const string & prefix, + const std::string & prefix, const ErrPos & errPos, const LinesOfCode & loc) { diff --git a/src/libutil/error.hh b/src/libutil/error.hh index 6fe5e4857..d55e1d701 100644 --- a/src/libutil/error.hh +++ b/src/libutil/error.hh @@ -61,16 +61,16 @@ typedef enum { // the lines of code surrounding an error. struct LinesOfCode { - std::optional prevLineOfCode; - std::optional errLineOfCode; - std::optional nextLineOfCode; + std::optional prevLineOfCode; + std::optional errLineOfCode; + std::optional nextLineOfCode; }; // ErrPos indicates the location of an error in a nix file. struct ErrPos { int line = 0; int column = 0; - string file; + std::string file; FileOrigin origin; operator bool() const @@ -80,7 +80,7 @@ struct ErrPos { // convert from the Pos struct, found in libexpr. template - ErrPos& operator=(const P &pos) + ErrPos & operator=(const P & pos) { origin = pos.origin; line = pos.line; @@ -94,7 +94,7 @@ struct ErrPos { } template - ErrPos(const P &p) + ErrPos(const P & p) { *this = p; } @@ -107,15 +107,15 @@ struct Trace { struct ErrorInfo { Verbosity level; - string name; // FIXME: rename + std::string name; // FIXME: rename hintformat msg; std::optional errPos; std::list traces; - static std::optional programName; + static std::optional programName; }; -std::ostream& showErrorInfo(std::ostream &out, const ErrorInfo &einfo, bool showTrace); +std::ostream & showErrorInfo(std::ostream & out, const ErrorInfo & einfo, bool showTrace); /* BaseError should generally not be caught, as it has Interrupted as a subclass. Catch Error instead. */ @@ -124,8 +124,8 @@ class BaseError : public std::exception protected: mutable ErrorInfo err; - mutable std::optional what_; - const string& calcWhat() const; + mutable std::optional what_; + const std::string & calcWhat() const; public: unsigned int status = 1; // exit status @@ -162,11 +162,11 @@ public: const char * what() const noexcept override { return calcWhat().c_str(); } #endif - const string & msg() const { return calcWhat(); } + const std::string & msg() const { return calcWhat(); } const ErrorInfo & info() const { calcWhat(); return err; } template - BaseError & addTrace(std::optional e, const string &fs, const Args & ... args) + BaseError & addTrace(std::optional e, const std::string & fs, const Args & ... args) { return addTrace(e, hintfmt(fs, args...)); } diff --git a/src/libutil/fmt.hh b/src/libutil/fmt.hh index a7126fb65..0821b3b74 100644 --- a/src/libutil/fmt.hh +++ b/src/libutil/fmt.hh @@ -10,7 +10,6 @@ namespace nix { /* Inherit some names from other namespaces for convenience. */ -using std::string; using boost::format; @@ -21,8 +20,8 @@ struct nop { template nop(T...) {} }; struct FormatOrString { - string s; - FormatOrString(const string & s) : s(s) { }; + std::string s; + FormatOrString(std::string s) : s(std::move(s)) { }; template FormatOrString(const F & f) : s(f.str()) { }; FormatOrString(const char * s) : s(s) { }; @@ -102,7 +101,7 @@ std::ostream & operator<<(std::ostream & out, const normaltxt & y) class hintformat { public: - hintformat(const string & format) : fmt(format) + hintformat(const std::string & format) : fmt(format) { fmt.exceptions(boost::io::all_error_bits ^ boost::io::too_many_args_bit ^ diff --git a/src/libutil/hash.cc b/src/libutil/hash.cc index 6ed00d43c..a4d632161 100644 --- a/src/libutil/hash.cc +++ b/src/libutil/hash.cc @@ -66,31 +66,31 @@ bool Hash::operator < (const Hash & h) const } -const string base16Chars = "0123456789abcdef"; +const std::string base16Chars = "0123456789abcdef"; -static string printHash16(const Hash & hash) +static std::string printHash16(const Hash & hash) { char buf[hash.hashSize * 2]; for (unsigned int i = 0; i < hash.hashSize; i++) { buf[i * 2] = base16Chars[hash.hash[i] >> 4]; buf[i * 2 + 1] = base16Chars[hash.hash[i] & 0x0f]; } - return string(buf, hash.hashSize * 2); + return std::string(buf, hash.hashSize * 2); } // omitted: E O U T -const string base32Chars = "0123456789abcdfghijklmnpqrsvwxyz"; +const std::string base32Chars = "0123456789abcdfghijklmnpqrsvwxyz"; -static string printHash32(const Hash & hash) +static std::string printHash32(const Hash & hash) { assert(hash.hashSize); size_t len = hash.base32Len(); assert(len); - string s; + std::string s; s.reserve(len); for (int n = (int) len - 1; n >= 0; n--) { @@ -107,7 +107,7 @@ static string printHash32(const Hash & hash) } -string printHash16or32(const Hash & hash) +std::string printHash16or32(const Hash & hash) { assert(hash.type); return hash.to_string(hash.type == htMD5 ? Base16 : Base32, false); @@ -151,7 +151,8 @@ Hash Hash::parseSRI(std::string_view original) { } // Mutates the string to eliminate the prefixes when found -static std::pair, bool> getParsedTypeAndSRI(std::string_view & rest) { +static std::pair, bool> getParsedTypeAndSRI(std::string_view & rest) +{ bool isSRI = false; // Parse the has type before the separater, if there was one. @@ -402,7 +403,7 @@ HashType parseHashType(std::string_view s) throw UsageError("unknown hash algorithm '%1%'", s); } -string printHashType(HashType ht) +std::string printHashType(HashType ht) { switch (ht) { case htMD5: return "md5"; diff --git a/src/libutil/hash.hh b/src/libutil/hash.hh index dff46542f..56b5938b3 100644 --- a/src/libutil/hash.hh +++ b/src/libutil/hash.hh @@ -20,7 +20,7 @@ const int sha512HashSize = 64; extern std::set hashTypes; -extern const string base32Chars; +extern const std::string base32Chars; enum Base : int { Base64, Base32, Base16, SRI }; @@ -110,7 +110,7 @@ public: Hash newHashAllowEmpty(std::string_view hashStr, std::optional ht); /* Print a hash in base-16 if it's MD5, or base-32 otherwise. */ -string printHash16or32(const Hash & hash); +std::string printHash16or32(const Hash & hash); /* Compute the hash of the given string. */ Hash hashString(HashType ht, std::string_view s); @@ -135,7 +135,7 @@ HashType parseHashType(std::string_view s); std::optional parseHashTypeOpt(std::string_view s); /* And the reverse. */ -string printHashType(HashType ht); +std::string printHashType(HashType ht); union Ctx; diff --git a/src/libutil/logging.cc b/src/libutil/logging.cc index f8a121ed1..74ee2f063 100644 --- a/src/libutil/logging.cc +++ b/src/libutil/logging.cc @@ -113,7 +113,7 @@ void warnOnce(bool & haveWarned, const FormatOrString & fs) } } -void writeToStderr(const string & s) +void writeToStderr(std::string_view s) { try { writeFull(STDERR_FILENO, s, false); diff --git a/src/libutil/logging.hh b/src/libutil/logging.hh index 5560d2bed..bd28036ae 100644 --- a/src/libutil/logging.hh +++ b/src/libutil/logging.hh @@ -216,6 +216,6 @@ inline void warn(const std::string & fs, const Args & ... args) void warnOnce(bool & haveWarned, const FormatOrString & fs); -void writeToStderr(const string & s); +void writeToStderr(std::string_view s); } diff --git a/src/libutil/serialise.cc b/src/libutil/serialise.cc index fe703de06..6445b3f1b 100644 --- a/src/libutil/serialise.cc +++ b/src/libutil/serialise.cc @@ -391,7 +391,7 @@ size_t readString(char * buf, size_t max, Source & source) } -string readString(Source & source, size_t max) +std::string readString(Source & source, size_t max) { auto len = readNum(source); if (len > max) throw SerialisationError("string is too long"); @@ -401,7 +401,7 @@ string readString(Source & source, size_t max) return res; } -Source & operator >> (Source & in, string & s) +Source & operator >> (Source & in, std::string & s) { s = readString(in); return in; diff --git a/src/libutil/serialise.hh b/src/libutil/serialise.hh index fdd35aa00..13da26c6a 100644 --- a/src/libutil/serialise.hh +++ b/src/libutil/serialise.hh @@ -364,10 +364,10 @@ inline uint64_t readLongLong(Source & source) void readPadding(size_t len, Source & source); size_t readString(char * buf, size_t max, Source & source); -string readString(Source & source, size_t max = std::numeric_limits::max()); +std::string readString(Source & source, size_t max = std::numeric_limits::max()); template T readStrings(Source & source); -Source & operator >> (Source & in, string & s); +Source & operator >> (Source & in, std::string & s); template Source & operator >> (Source & in, T & n) diff --git a/src/libutil/tests/url.cc b/src/libutil/tests/url.cc index aff58e9ee..f20e2dc41 100644 --- a/src/libutil/tests/url.cc +++ b/src/libutil/tests/url.cc @@ -5,9 +5,9 @@ namespace nix { /* ----------- tests for url.hh --------------------------------------------------*/ - string print_map(std::map m) { - std::map::iterator it; - string s = "{ "; + std::string print_map(std::map m) { + std::map::iterator it; + std::string s = "{ "; for (it = m.begin(); it != m.end(); ++it) { s += "{ "; s += it->first; @@ -262,21 +262,21 @@ namespace nix { * --------------------------------------------------------------------------*/ TEST(percentDecode, decodesUrlEncodedString) { - string s = "==@=="; - string d = percentDecode("%3D%3D%40%3D%3D"); + std::string s = "==@=="; + std::string d = percentDecode("%3D%3D%40%3D%3D"); ASSERT_EQ(d, s); } TEST(percentDecode, multipleDecodesAreIdempotent) { - string once = percentDecode("%3D%3D%40%3D%3D"); - string twice = percentDecode(once); + std::string once = percentDecode("%3D%3D%40%3D%3D"); + std::string twice = percentDecode(once); ASSERT_EQ(once, twice); } TEST(percentDecode, trailingPercent) { - string s = "==@==%"; - string d = percentDecode("%3D%3D%40%3D%3D%25"); + std::string s = "==@==%"; + std::string d = percentDecode("%3D%3D%40%3D%3D%25"); ASSERT_EQ(d, s); } diff --git a/src/libutil/types.hh b/src/libutil/types.hh index bea2673ca..00ba567c6 100644 --- a/src/libutil/types.hh +++ b/src/libutil/types.hh @@ -14,6 +14,7 @@ namespace nix { typedef std::list Strings; typedef std::set StringSet; typedef std::map StringMap; +typedef std::map StringPairs; /* Paths are just strings. */ typedef std::string Path; diff --git a/src/libutil/util.cc b/src/libutil/util.cc index b172e0554..88c5ae806 100644 --- a/src/libutil/util.cc +++ b/src/libutil/util.cc @@ -110,13 +110,13 @@ Path canonPath(PathView path, bool resolveSymlinks) { assert(path != ""); - string s; + std::string s; s.reserve(256); if (path[0] != '/') throw Error("not an absolute path: '%1%'", path); - string temp; + std::string temp; /* Count the number of times we follow a symlink and stop at some arbitrary (but high) limit to prevent infinite loops. */ @@ -142,7 +142,7 @@ Path canonPath(PathView path, bool resolveSymlinks) /* Normal component; copy it. */ else { s += '/'; - if (const auto slash = path.find('/'); slash == string::npos) { + if (const auto slash = path.find('/'); slash == std::string::npos) { s += path; path = {}; } else { @@ -175,7 +175,7 @@ Path canonPath(PathView path, bool resolveSymlinks) Path dirOf(const PathView path) { Path::size_type pos = path.rfind('/'); - if (pos == string::npos) + if (pos == std::string::npos) return "."; return pos == 0 ? "/" : Path(path, 0, pos); } @@ -191,7 +191,7 @@ std::string_view baseNameOf(std::string_view path) last -= 1; auto pos = path.rfind('/', last); - if (pos == string::npos) + if (pos == std::string::npos) pos = 0; else pos += 1; @@ -249,7 +249,7 @@ Path readLink(const Path & path) else throw SysError("reading symbolic link '%1%'", path); else if (rlSize < bufSize) - return string(buf.data(), rlSize); + return std::string(buf.data(), rlSize); } } @@ -269,7 +269,7 @@ DirEntries readDirectory(DIR *dir, const Path & path) struct dirent * dirent; while (errno = 0, dirent = readdir(dir)) { /* sic */ checkInterrupt(); - string name = dirent->d_name; + std::string name = dirent->d_name; if (name == "." || name == "..") continue; entries.emplace_back(name, dirent->d_ino, #ifdef HAVE_STRUCT_DIRENT_D_TYPE @@ -303,7 +303,7 @@ unsigned char getFileType(const Path & path) } -string readFile(int fd) +std::string readFile(int fd) { struct stat st; if (fstat(fd, &st) == -1) @@ -313,7 +313,7 @@ string readFile(int fd) } -string readFile(const Path & path) +std::string readFile(const Path & path) { AutoCloseFD fd = open(path.c_str(), O_RDONLY | O_CLOEXEC); if (!fd) @@ -366,9 +366,9 @@ void writeFile(const Path & path, Source & source, mode_t mode) } } -string readLine(int fd) +std::string readLine(int fd) { - string s; + std::string s; while (1) { checkInterrupt(); char ch; @@ -387,7 +387,7 @@ string readLine(int fd) } -void writeLine(int fd, string s) +void writeLine(int fd, std::string s) { s += '\n'; writeFull(fd, s); @@ -398,7 +398,7 @@ static void _deletePath(int parentfd, const Path & path, uint64_t & bytesFreed) { checkInterrupt(); - string name(baseNameOf(path)); + std::string name(baseNameOf(path)); struct stat st; if (fstatat(parentfd, name.c_str(), &st, AT_SYMLINK_NOFOLLOW) == -1) { @@ -566,8 +566,8 @@ Path getConfigDir() std::vector getConfigDirs() { Path configHome = getConfigDir(); - string configDirs = getEnv("XDG_CONFIG_DIRS").value_or("/etc/xdg"); - std::vector result = tokenizeString>(configDirs, ":"); + auto configDirs = getEnv("XDG_CONFIG_DIRS").value_or("/etc/xdg"); + std::vector result = tokenizeString>(configDirs, ":"); result.insert(result.begin(), configHome); return result; } @@ -670,7 +670,7 @@ void writeFull(int fd, std::string_view s, bool allowInterrupts) } -string drainFD(int fd, bool block, const size_t reserveSize) +std::string drainFD(int fd, bool block, const size_t reserveSize) { // the parser needs two extra bytes to append terminating characters, other users will // not care very much about the extra memory. @@ -719,7 +719,7 @@ void drainFD(int fd, Sink & sink, bool block) AutoDelete::AutoDelete() : del{false} {} -AutoDelete::AutoDelete(const string & p, bool recursive) : path(p) +AutoDelete::AutoDelete(const std::string & p, bool recursive) : path(p) { del = true; this->recursive = recursive; @@ -1036,7 +1036,7 @@ std::vector stringsToCharPtrs(const Strings & ss) return res; } -string runProgram(Path program, bool searchPath, const Strings & args, +std::string runProgram(Path program, bool searchPath, const Strings & args, const std::optional & input) { auto res = runProgram(RunOptions {.program = program, .searchPath = searchPath, .args = args, .input = input}); @@ -1238,11 +1238,11 @@ void _interrupted() template C tokenizeString(std::string_view s, std::string_view separators) { C result; - string::size_type pos = s.find_first_not_of(separators, 0); - while (pos != string::npos) { - string::size_type end = s.find_first_of(separators, pos + 1); - if (end == string::npos) end = s.size(); - result.insert(result.end(), string(s, pos, end - pos)); + auto pos = s.find_first_not_of(separators, 0); + while (pos != std::string::npos) { + auto end = s.find_first_of(separators, pos + 1); + if (end == std::string::npos) end = s.size(); + result.insert(result.end(), std::string(s, pos, end - pos)); pos = s.find_first_not_of(separators, end); } return result; @@ -1250,29 +1250,30 @@ template C tokenizeString(std::string_view s, std::string_view separato template Strings tokenizeString(std::string_view s, std::string_view separators); template StringSet tokenizeString(std::string_view s, std::string_view separators); -template std::vector tokenizeString(std::string_view s, std::string_view separators); +template std::vector tokenizeString(std::string_view s, std::string_view separators); -string chomp(std::string_view s) +std::string chomp(std::string_view s) { size_t i = s.find_last_not_of(" \n\r\t"); - return i == string::npos ? "" : string(s, 0, i + 1); + return i == std::string_view::npos ? "" : std::string(s, 0, i + 1); } -string trim(const string & s, const string & whitespace) +std::string trim(std::string_view s, std::string_view whitespace) { auto i = s.find_first_not_of(whitespace); - if (i == string::npos) return ""; + if (i == std::string_view::npos) return ""; auto j = s.find_last_not_of(whitespace); - return string(s, i, j == string::npos ? j : j - i + 1); + return std::string(s, i, j == std::string::npos ? j : j - i + 1); } -string replaceStrings(std::string_view s, - const std::string & from, const std::string & to) +std::string replaceStrings( + std::string res, + std::string_view from, + std::string_view to) { - string res(s); if (from.empty()) return res; size_t pos = 0; while ((pos = res.find(from, pos)) != std::string::npos) { @@ -1283,20 +1284,19 @@ string replaceStrings(std::string_view s, } -std::string rewriteStrings(const std::string & _s, const StringMap & rewrites) +std::string rewriteStrings(std::string s, const StringMap & rewrites) { - auto s = _s; for (auto & i : rewrites) { if (i.first == i.second) continue; size_t j = 0; - while ((j = s.find(i.first, j)) != string::npos) + while ((j = s.find(i.first, j)) != std::string::npos) s.replace(j, i.first.size(), i.second); } return s; } -string statusToString(int status) +std::string statusToString(int status) { if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { if (WIFEXITED(status)) @@ -1448,9 +1448,9 @@ std::string filterANSIEscapes(const std::string & s, bool filterAll, unsigned in constexpr char base64Chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -string base64Encode(std::string_view s) +std::string base64Encode(std::string_view s) { - string res; + std::string res; int data = 0, nbits = 0; for (char c : s) { @@ -1469,7 +1469,7 @@ string base64Encode(std::string_view s) } -string base64Decode(std::string_view s) +std::string base64Decode(std::string_view s) { constexpr char npos = -1; constexpr std::array base64DecodeChars = [&]() { @@ -1481,7 +1481,7 @@ string base64Decode(std::string_view s) return result; }(); - string res; + std::string res; unsigned int d = 0, bits = 0; for (char c : s) { @@ -1835,7 +1835,7 @@ void connect(int fd, const std::string & path) } -string showBytes(uint64_t bytes) +std::string showBytes(uint64_t bytes) { return fmt("%.2f MiB", bytes / (1024.0 * 1024.0)); } @@ -1846,7 +1846,7 @@ void commonChildInit(Pipe & logPipe) { logger = makeSimpleLogger(); - const static string pathNullDevice = "/dev/null"; + const static std::string pathNullDevice = "/dev/null"; restoreProcessContext(false); /* Put the child in a separate session (and thus a separate diff --git a/src/libutil/util.hh b/src/libutil/util.hh index a949e6424..20591952d 100644 --- a/src/libutil/util.hh +++ b/src/libutil/util.hh @@ -92,11 +92,11 @@ bool isLink(const Path & path); removed. */ struct DirEntry { - string name; + std::string name; ino_t ino; unsigned char type; // one of DT_* - DirEntry(const string & name, ino_t ino, unsigned char type) - : name(name), ino(ino), type(type) { } + DirEntry(std::string name, ino_t ino, unsigned char type) + : name(std::move(name)), ino(ino), type(type) { } }; typedef std::vector DirEntries; @@ -106,8 +106,8 @@ DirEntries readDirectory(const Path & path); unsigned char getFileType(const Path & path); /* Read the contents of a file into a string. */ -string readFile(int fd); -string readFile(const Path & path); +std::string readFile(int fd); +std::string readFile(const Path & path); void readFile(const Path & path, Sink & sink); /* Write a string to a file. */ @@ -116,10 +116,10 @@ void writeFile(const Path & path, std::string_view s, mode_t mode = 0666); void writeFile(const Path & path, Source & source, mode_t mode = 0666); /* Read a line from a file descriptor. */ -string readLine(int fd); +std::string readLine(int fd); /* Write a line to a file descriptor. */ -void writeLine(int fd, string s); +void writeLine(int fd, std::string s); /* Delete a path; i.e., in the case of a directory, it is deleted recursively. It's not an error if the path does not exist. The @@ -170,7 +170,7 @@ MakeError(EndOfFile, Error); /* Read a file descriptor until EOF occurs. */ -string drainFD(int fd, bool block = true, const size_t reserveSize=0); +std::string drainFD(int fd, bool block = true, const size_t reserveSize=0); void drainFD(int fd, Sink & sink, bool block = true); @@ -268,7 +268,7 @@ void killUser(uid_t uid); pid to the caller. */ struct ProcessOptions { - string errorPrefix = ""; + std::string errorPrefix = ""; bool dieWithParent = true; bool runExitHandlers = false; bool allowVfork = false; @@ -279,7 +279,7 @@ pid_t startProcess(std::function fun, const ProcessOptions & options = P /* Run a program and return its stdout in a string (i.e., like the shell backtick operator). */ -string runProgram(Path program, bool searchPath = false, +std::string runProgram(Path program, bool searchPath = false, const Strings & args = Strings(), const std::optional & input = {}); @@ -378,12 +378,12 @@ template C tokenizeString(std::string_view s, std::string_view separato /* Concatenate the given strings with a separator between the elements. */ template -string concatStringsSep(const std::string_view sep, const C & ss) +std::string concatStringsSep(const std::string_view sep, const C & ss) { size_t size = 0; // need a cast to string_view since this is also called with Symbols for (const auto & s : ss) size += sep.size() + std::string_view(s).size(); - string s; + std::string s; s.reserve(size); for (auto & i : ss) { if (s.size() != 0) s += sep; @@ -394,7 +394,7 @@ string concatStringsSep(const std::string_view sep, const C & ss) template auto concatStrings(Parts && ... parts) - -> std::enable_if_t<(... && std::is_convertible_v), string> + -> std::enable_if_t<(... && std::is_convertible_v), std::string> { std::string_view views[sizeof...(parts)] = { parts... }; return concatStringsSep({}, views); @@ -413,24 +413,26 @@ template Strings quoteStrings(const C & c) /* Remove trailing whitespace from a string. FIXME: return std::string_view. */ -string chomp(std::string_view s); +std::string chomp(std::string_view s); /* Remove whitespace from the start and end of a string. */ -string trim(const string & s, const string & whitespace = " \n\r\t"); +std::string trim(std::string_view s, std::string_view whitespace = " \n\r\t"); /* Replace all occurrences of a string inside another string. */ -string replaceStrings(std::string_view s, - const std::string & from, const std::string & to); +std::string replaceStrings( + std::string s, + std::string_view from, + std::string_view to); -std::string rewriteStrings(const std::string & s, const StringMap & rewrites); +std::string rewriteStrings(std::string s, const StringMap & rewrites); /* Convert the exit status of a child as returned by wait() into an error string. */ -string statusToString(int status); +std::string statusToString(int status); bool statusOk(int status); @@ -525,8 +527,8 @@ std::string filterANSIEscapes(const std::string & s, /* Base64 encoding/decoding. */ -string base64Encode(std::string_view s); -string base64Decode(std::string_view s); +std::string base64Encode(std::string_view s); +std::string base64Decode(std::string_view s); /* Remove common leading whitespace from the lines in the string diff --git a/src/nix-build/nix-build.cc b/src/nix-build/nix-build.cc index aeabdcdd4..3d189f934 100755 --- a/src/nix-build/nix-build.cc +++ b/src/nix-build/nix-build.cc @@ -32,11 +32,11 @@ extern char * * environ __attribute__((weak)); /* Recreate the effect of the perl shellwords function, breaking up a * string into arguments like a shell word, including escapes */ -std::vector shellwords(const string & s) +static std::vector shellwords(const std::string & s) { std::regex whitespace("^(\\s+).*"); auto begin = s.cbegin(); - std::vector res; + std::vector res; std::string cur; enum state { sBegin, @@ -96,14 +96,14 @@ static void main_nix_build(int argc, char * * argv) auto inShebang = false; std::string script; - std::vector savedArgs; + std::vector savedArgs; AutoDelete tmpDir(createTempDir("", myName)); std::string outLink = "./result"; // List of environment variables kept for --pure - std::set keepVars{ + std::set keepVars{ "HOME", "XDG_RUNTIME_DIR", "USER", "LOGNAME", "DISPLAY", "WAYLAND_DISPLAY", "WAYLAND_SOCKET", "PATH", "TERM", "IN_NIX_SHELL", "NIX_SHELL_PRESERVE_PROMPT", "TZ", "PAGER", "NIX_BUILD_SHELL", "SHLVL", @@ -384,7 +384,9 @@ static void main_nix_build(int argc, char * * argv) // Build or fetch all dependencies of the derivation. for (const auto & input : drv.inputDrvs) if (std::all_of(envExclude.cbegin(), envExclude.cend(), - [&](const string & exclude) { return !std::regex_search(store->printStorePath(input.first), std::regex(exclude)); })) + [&](const std::string & exclude) { + return !std::regex_search(store->printStorePath(input.first), std::regex(exclude)); + })) { pathsToBuild.push_back({input.first, input.second}); pathsToCopy.insert(input.first); @@ -437,7 +439,7 @@ static void main_nix_build(int argc, char * * argv) for (auto & var : drv.env) if (passAsFile.count(var.first)) { keepTmp = true; - string fn = ".attr-" + std::to_string(fileNr++); + auto fn = ".attr-" + std::to_string(fileNr++); Path p = (Path) tmpDir + "/" + fn; writeFile(p, var.second); env[var.first + "Path"] = p; @@ -514,7 +516,7 @@ static void main_nix_build(int argc, char * * argv) (pure ? "" : "PATH=$PATH:$p; unset p; "), shellEscape(dirOf(*shell)), shellEscape(*shell), - (getenv("TZ") ? (string("export TZ=") + shellEscape(getenv("TZ")) + "; ") : ""), + (getenv("TZ") ? (std::string("export TZ=") + shellEscape(getenv("TZ")) + "; ") : ""), envCommand); vomit("Sourcing nix-shell with file %s and contents:\n%s", rcfile, rc); writeFile(rcfile, rc); diff --git a/src/nix-channel/nix-channel.cc b/src/nix-channel/nix-channel.cc index eae15885a..f46b90b90 100755 --- a/src/nix-channel/nix-channel.cc +++ b/src/nix-channel/nix-channel.cc @@ -11,7 +11,7 @@ using namespace nix; -typedef std::map Channels; +typedef std::map Channels; static Channels channels; static Path channelsList; @@ -22,11 +22,11 @@ static void readChannels() if (!pathExists(channelsList)) return; auto channelsFile = readFile(channelsList); - for (const auto & line : tokenizeString>(channelsFile, "\n")) { + for (const auto & line : tokenizeString>(channelsFile, "\n")) { chomp(line); if (std::regex_search(line, std::regex("^\\s*\\#"))) continue; - auto split = tokenizeString>(line, " "); + auto split = tokenizeString>(line, " "); auto url = std::regex_replace(split[0], std::regex("/*$"), ""); auto name = split.size() > 1 ? split[1] : std::string(baseNameOf(url)); channels[name] = url; @@ -44,7 +44,7 @@ static void writeChannels() } // Adds a channel. -static void addChannel(const string & url, const string & name) +static void addChannel(const std::string & url, const std::string & name) { if (!regex_search(url, std::regex("^(file|http|https)://"))) throw Error("invalid channel URL '%1%'", url); @@ -58,7 +58,7 @@ static void addChannel(const string & url, const string & name) static Path profile; // Remove a channel. -static void removeChannel(const string & name) +static void removeChannel(const std::string & name) { readChannels(); channels.erase(name); @@ -96,7 +96,7 @@ static void update(const StringSet & channelNames) std::smatch match; auto urlBase = std::string(baseNameOf(url)); if (std::regex_search(urlBase, match, std::regex("(-\\d.*)$"))) - cname = cname + (string) match[1]; + cname = cname + (std::string) match[1]; std::string extraAttrs; @@ -176,7 +176,7 @@ static int main_nix_channel(int argc, char ** argv) cUpdate, cRollback } cmd = cNone; - std::vector args; + std::vector args; parseCmdLine(argc, argv, [&](Strings::iterator & arg, const Strings::iterator & end) { if (*arg == "--help") { showManPage("nix-channel"); diff --git a/src/nix-collect-garbage/nix-collect-garbage.cc b/src/nix-collect-garbage/nix-collect-garbage.cc index 4f953fab4..48c030b18 100644 --- a/src/nix-collect-garbage/nix-collect-garbage.cc +++ b/src/nix-collect-garbage/nix-collect-garbage.cc @@ -36,7 +36,7 @@ void removeOldGenerations(std::string dir) } catch (SysError & e) { if (e.errNo == ENOENT) continue; } - if (link.find("link") != string::npos) { + if (link.find("link") != std::string::npos) { printInfo(format("removing old generations of profile %1%") % path); if (deleteOlderThan != "") deleteGenerationsOlderThan(path, deleteOlderThan, dryRun); diff --git a/src/nix-env/nix-env.cc b/src/nix-env/nix-env.cc index f83edb6a1..12e08bbe1 100644 --- a/src/nix-env/nix-env.cc +++ b/src/nix-env/nix-env.cc @@ -46,7 +46,7 @@ struct InstallSourceInfo InstallSourceType type; Path nixExprPath; /* for srcNixExprDrvs, srcNixExprs */ Path profile; /* for srcProfile */ - string systemFilter; /* for srcNixExprDrvs */ + std::string systemFilter; /* for srcNixExprDrvs */ Bindings * autoArgs; }; @@ -59,7 +59,7 @@ struct Globals bool dryRun; bool preserveInstalled; bool removeAll; - string forceName; + std::string forceName; bool prebuiltOnly; }; @@ -68,8 +68,8 @@ typedef void (* Operation) (Globals & globals, Strings opFlags, Strings opArgs); -static string needArg(Strings::iterator & i, - Strings & args, const string & arg) +static std::string needArg(Strings::iterator & i, + Strings & args, const std::string & arg) { if (i == args.end()) throw UsageError("'%1%' requires an argument", arg); return *i++; @@ -77,7 +77,7 @@ static string needArg(Strings::iterator & i, static bool parseInstallSourceOptions(Globals & globals, - Strings::iterator & i, Strings & args, const string & arg) + Strings::iterator & i, Strings & args, const std::string & arg) { if (arg == "--from-expression" || arg == "-E") globals.instSource.type = srcNixExprs; @@ -124,9 +124,9 @@ static void getAllExprs(EvalState & state, otherwise the attribute cannot be selected with the `-A' option. Useful if you want to stick a Nix expression directly in ~/.nix-defexpr. */ - string attrName = i; + std::string attrName = i; if (hasSuffix(attrName, ".nix")) - attrName = string(attrName, 0, attrName.size() - 4); + attrName = std::string(attrName, 0, attrName.size() - 4); if (!seen.insert(attrName).second) { printError("warning: name collision in input Nix expressions, skipping '%1%'", path2); continue; @@ -175,8 +175,8 @@ static void loadSourceExpr(EvalState & state, const Path & path, Value & v) static void loadDerivations(EvalState & state, Path nixExprPath, - string systemFilter, Bindings & autoArgs, - const string & pathPrefix, DrvInfos & elems) + std::string systemFilter, Bindings & autoArgs, + const std::string & pathPrefix, DrvInfos & elems) { Value vRoot; loadSourceExpr(state, nixExprPath, vRoot); @@ -343,9 +343,9 @@ static DrvInfos filterBySelector(EvalState & state, const DrvInfos & allElems, if (selector.hits == 0 && selector.fullName != "*") { const auto prefixHits = searchByPrefix(allElems, selector.name); - + if (prefixHits.empty()) { - throw Error("selector '%1%' matches no derivations", selector.fullName); + throw Error("selector '%1%' matches no derivations", selector.fullName); } else { std::string suggestionMessage = ", maybe you meant:"; for (const auto & drvName : prefixHits) { @@ -360,9 +360,9 @@ static DrvInfos filterBySelector(EvalState & state, const DrvInfos & allElems, } -static bool isPath(const string & s) +static bool isPath(std::string_view s) { - return s.find('/') != string::npos; + return s.find('/') != std::string_view::npos; } @@ -433,8 +433,8 @@ static void queryInstSources(EvalState & state, auto outputs = state.store->queryDerivationOutputMap(path); elem.setOutPath(state.store->printStorePath(outputs.at("out"))); if (name.size() >= drvExtension.size() && - string(name, name.size() - drvExtension.size()) == drvExtension) - name = string(name, 0, name.size() - drvExtension.size()); + std::string(name, name.size() - drvExtension.size()) == drvExtension) + name = name.substr(0, name.size() - drvExtension.size()); } else elem.setOutPath(state.store->printStorePath(path)); @@ -515,7 +515,7 @@ static void installDerivations(Globals & globals, while (true) { - string lockToken = optimisticLockProfile(profile); + auto lockToken = optimisticLockProfile(profile); DrvInfos allElems(newElems); @@ -551,7 +551,7 @@ static void installDerivations(Globals & globals, static void opInstall(Globals & globals, Strings opFlags, Strings opArgs) { for (Strings::iterator i = opFlags.begin(); i != opFlags.end(); ) { - string arg = *i++; + auto arg = *i++; if (parseInstallSourceOptions(globals, i, opFlags, arg)) ; else if (arg == "--preserve-installed" || arg == "-P") globals.preserveInstalled = true; @@ -578,7 +578,7 @@ static void upgradeDerivations(Globals & globals, name and a higher version number. */ while (true) { - string lockToken = optimisticLockProfile(globals.profile); + auto lockToken = optimisticLockProfile(globals.profile); DrvInfos installedElems = queryInstalled(*globals.state, globals.profile); @@ -606,7 +606,7 @@ static void upgradeDerivations(Globals & globals, take the one with the highest version. Do not upgrade if it would decrease the priority. */ DrvInfos::iterator bestElem = availElems.end(); - string bestVersion; + std::string bestVersion; for (auto j = availElems.begin(); j != availElems.end(); ++j) { if (comparePriorities(*globals.state, i, *j) > 0) continue; @@ -662,7 +662,7 @@ static void opUpgrade(Globals & globals, Strings opFlags, Strings opArgs) { UpgradeType upgradeType = utLt; for (Strings::iterator i = opFlags.begin(); i != opFlags.end(); ) { - string arg = *i++; + std::string arg = *i++; if (parseInstallSourceOptions(globals, i, opFlags, arg)) ; else if (arg == "--lt") upgradeType = utLt; else if (arg == "--leq") upgradeType = utLeq; @@ -676,7 +676,7 @@ static void opUpgrade(Globals & globals, Strings opFlags, Strings opArgs) static void setMetaFlag(EvalState & state, DrvInfo & drv, - const string & name, const string & value) + const std::string & name, const std::string & value) { auto v = state.allocValue(); v->mkString(value); @@ -692,12 +692,12 @@ static void opSetFlag(Globals & globals, Strings opFlags, Strings opArgs) throw UsageError("not enough arguments to '--set-flag'"); Strings::iterator arg = opArgs.begin(); - string flagName = *arg++; - string flagValue = *arg++; + std::string flagName = *arg++; + std::string flagValue = *arg++; DrvNames selectors = drvNamesFromArgs(Strings(arg, opArgs.end())); while (true) { - string lockToken = optimisticLockProfile(globals.profile); + std::string lockToken = optimisticLockProfile(globals.profile); DrvInfos installedElems = queryInstalled(*globals.state, globals.profile); @@ -728,7 +728,7 @@ static void opSet(Globals & globals, Strings opFlags, Strings opArgs) if (!store2) throw Error("--set is not supported for this Nix store"); for (Strings::iterator i = opFlags.begin(); i != opFlags.end(); ) { - string arg = *i++; + std::string arg = *i++; if (parseInstallSourceOptions(globals, i, opFlags, arg)) ; else throw UsageError("unknown flag '%1%'", arg); } @@ -769,7 +769,7 @@ static void uninstallDerivations(Globals & globals, Strings & selectors, Path & profile) { while (true) { - string lockToken = optimisticLockProfile(profile); + auto lockToken = optimisticLockProfile(profile); DrvInfos workingElems = queryInstalled(*globals.state, profile); @@ -855,11 +855,11 @@ void printTable(Table & table) Strings::iterator j; size_t column; for (j = i.begin(), column = 0; j != i.end(); ++j, ++column) { - string s = *j; + std::string s = *j; replace(s.begin(), s.end(), '\n', ' '); cout << s; if (column < nrColumns - 1) - cout << string(widths[column] - s.size() + 2, ' '); + cout << std::string(widths[column] - s.size() + 2, ' '); } cout << std::endl; } @@ -876,7 +876,7 @@ void printTable(Table & table) typedef enum { cvLess, cvEqual, cvGreater, cvUnavail } VersionDiff; static VersionDiff compareVersionAgainstSet( - const DrvInfo & elem, const DrvInfos & elems, string & version) + const DrvInfo & elem, const DrvInfos & elems, std::string & version) { DrvName name(elem.queryName()); @@ -958,7 +958,7 @@ static void queryJSON(Globals & globals, std::vector & elems, bool prin static void opQuery(Globals & globals, Strings opFlags, Strings opArgs) { Strings remaining; - string attrPath; + std::string attrPath; bool printStatus = false; bool printName = true; @@ -977,7 +977,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs) settings.readOnlyMode = true; /* makes evaluation a bit faster */ for (Strings::iterator i = opFlags.begin(); i != opFlags.end(); ) { - string arg = *i++; + auto arg = *i++; if (arg == "--status" || arg == "-s") printStatus = true; else if (arg == "--no-name") printName = false; else if (arg == "--system") printSystem = true; @@ -1094,7 +1094,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs) attrs["substitutable"] = hasSubs ? "1" : "0"; } else columns.push_back( - (string) (isInstalled ? "I" : "-") + (std::string) (isInstalled ? "I" : "-") + (isValid ? "P" : "-") + (hasSubs ? "S" : "-")); } @@ -1118,7 +1118,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs) same named packages in either the set of available elements, or the set of installed elements. !!! This is O(N * M), should be O(N * lg M). */ - string version; + std::string version; VersionDiff diff = compareVersionAgainstSet(i, otherElems, version); char ch; @@ -1136,7 +1136,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs) attrs["maxComparedVersion"] = version; } } else { - string column = (string) "" + ch + " " + version; + auto column = (std::string) "" + ch + " " + version; if (diff == cvGreater && tty) column = ANSI_RED + column + ANSI_NORMAL; columns.push_back(column); @@ -1150,7 +1150,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs) columns.push_back(i.querySystem()); if (printDrvPath) { - string drvPath = i.queryDrvPath(); + auto drvPath = i.queryDrvPath(); if (xmlOutput) { if (drvPath != "") attrs["drvPath"] = drvPath; } else @@ -1159,7 +1159,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs) if (printOutPath && !xmlOutput) { DrvInfo::Outputs outputs = i.queryOutputs(); - string s; + std::string s; for (auto & j : outputs) { if (!s.empty()) s += ';'; if (j.first != "out") { s += j.first; s += "="; } @@ -1169,7 +1169,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs) } if (printDescription) { - string descr = i.queryMetaString("description"); + auto descr = i.queryMetaString("description"); if (xmlOutput) { if (descr != "") attrs["description"] = descr; } else @@ -1331,12 +1331,12 @@ static void opDeleteGenerations(Globals & globals, Strings opFlags, Strings opAr if (opArgs.size() == 1 && opArgs.front() == "old") { deleteOldGenerations(globals.profile, globals.dryRun); - } else if (opArgs.size() == 1 && opArgs.front().find('d') != string::npos) { + } else if (opArgs.size() == 1 && opArgs.front().find('d') != std::string::npos) { deleteGenerationsOlderThan(globals.profile, opArgs.front(), globals.dryRun); - } else if (opArgs.size() == 1 && opArgs.front().find('+') != string::npos) { + } else if (opArgs.size() == 1 && opArgs.front().find('+') != std::string::npos) { if (opArgs.front().size() < 2) throw Error("invalid number of generations '%1%'", opArgs.front()); - string str_max = string(opArgs.front(), 1, opArgs.front().size()); + auto str_max = opArgs.front().substr(1); auto max = string2Int(str_max); if (!max || *max == 0) throw Error("invalid number of generations to keep '%1%'", opArgs.front()); @@ -1366,7 +1366,7 @@ static int main_nix_env(int argc, char * * argv) Strings opFlags, opArgs; Operation op = 0; RepairFlag repair = NoRepair; - string file; + std::string file; Globals globals; diff --git a/src/nix-env/user-env.cc b/src/nix-env/user-env.cc index 5842e6501..37e4086cb 100644 --- a/src/nix-env/user-env.cc +++ b/src/nix-env/user-env.cc @@ -32,7 +32,7 @@ DrvInfos queryInstalled(EvalState & state, const Path & userEnv) bool createUserEnv(EvalState & state, DrvInfos & elems, const Path & profile, bool keepDerivations, - const string & lockToken) + const std::string & lockToken) { /* Build the components in the user environment, if they don't exist already. */ diff --git a/src/nix-env/user-env.hh b/src/nix-env/user-env.hh index f188efe9b..10646f713 100644 --- a/src/nix-env/user-env.hh +++ b/src/nix-env/user-env.hh @@ -8,6 +8,6 @@ DrvInfos queryInstalled(EvalState & state, const Path & userEnv); bool createUserEnv(EvalState & state, DrvInfos & elems, const Path & profile, bool keepDerivations, - const string & lockToken); + const std::string & lockToken); } diff --git a/src/nix-instantiate/nix-instantiate.cc b/src/nix-instantiate/nix-instantiate.cc index a08683be1..12fc8baf9 100644 --- a/src/nix-instantiate/nix-instantiate.cc +++ b/src/nix-instantiate/nix-instantiate.cc @@ -64,7 +64,7 @@ void processExpr(EvalState & state, const Strings & attrPaths, Path drvPath = i.queryDrvPath(); /* What output do we want? */ - string outputName = i.queryOutputName(); + std::string outputName = i.queryOutputName(); if (outputName == "") throw Error("derivation '%1%' lacks an 'outputName' attribute ", drvPath); diff --git a/src/nix-store/dotgraph.cc b/src/nix-store/dotgraph.cc index 8b699f39b..577cadceb 100644 --- a/src/nix-store/dotgraph.cc +++ b/src/nix-store/dotgraph.cc @@ -10,37 +10,35 @@ using std::cout; namespace nix { -static string dotQuote(std::string_view s) +static std::string dotQuote(std::string_view s) { return "\"" + std::string(s) + "\""; } -static string nextColour() +static const std::string & nextColour() { static int n = 0; - static string colours[] = + static std::vector colours { "black", "red", "green", "blue" , "magenta", "burlywood" }; - return colours[n++ % (sizeof(colours) / sizeof(string))]; + return colours[n++ % colours.size()]; } -static string makeEdge(const string & src, const string & dst) +static std::string makeEdge(std::string_view src, std::string_view dst) { - format f = format("%1% -> %2% [color = %3%];\n") - % dotQuote(src) % dotQuote(dst) % dotQuote(nextColour()); - return f.str(); + return fmt("%1% -> %2% [color = %3%];\n", + dotQuote(src), dotQuote(dst), dotQuote(nextColour())); } -static string makeNode(const string & id, std::string_view label, - const string & colour) +static std::string makeNode(std::string_view id, std::string_view label, + std::string_view colour) { - format f = format("%1% [label = %2%, shape = box, " - "style = filled, fillcolor = %3%];\n") - % dotQuote(id) % dotQuote(label) % dotQuote(colour); - return f.str(); + return fmt("%1% [label = %2%, shape = box, " + "style = filled, fillcolor = %3%];\n", + dotQuote(id), dotQuote(label), dotQuote(colour)); } diff --git a/src/nix-store/graphml.cc b/src/nix-store/graphml.cc index 8ca5c9c8d..425d61e53 100644 --- a/src/nix-store/graphml.cc +++ b/src/nix-store/graphml.cc @@ -19,20 +19,20 @@ static inline std::string_view xmlQuote(std::string_view s) } -static string symbolicName(const std::string & p) +static std::string symbolicName(std::string_view p) { - return string(p, p.find('-') + 1); + return std::string(p.substr(0, p.find('-') + 1)); } -static string makeEdge(std::string_view src, std::string_view dst) +static std::string makeEdge(std::string_view src, std::string_view dst) { return fmt(" \n", xmlQuote(src), xmlQuote(dst)); } -static string makeNode(const ValidPathInfo & info) +static std::string makeNode(const ValidPathInfo & info) { return fmt( " \n" diff --git a/src/nix-store/nix-store.cc b/src/nix-store/nix-store.cc index f0ce0368a..ecd7279e9 100644 --- a/src/nix-store/nix-store.cc +++ b/src/nix-store/nix-store.cc @@ -208,8 +208,8 @@ static void opPrintFixedPath(Strings opFlags, Strings opArgs) Strings::iterator i = opArgs.begin(); HashType hashAlgo = parseHashType(*i++); - string hash = *i++; - string name = *i++; + std::string hash = *i++; + std::string name = *i++; cout << fmt("%s\n", store->printStorePath(store->makeFixedOutputPath(recursive, Hash::parseAny(hash, hashAlgo), name))); } @@ -238,7 +238,7 @@ static StorePathSet maybeUseOutputs(const StorePath & storePath, bool useOutput, graph. Topological sorting is used to keep the tree relatively flat. */ static void printTree(const StorePath & path, - const string & firstPad, const string & tailPad, StorePathSet & done) + const std::string & firstPad, const std::string & tailPad, StorePathSet & done) { if (!done.insert(path).second) { cout << fmt("%s%s [...]\n", firstPad, store->printStorePath(path)); @@ -277,7 +277,7 @@ static void opQuery(Strings opFlags, Strings opArgs) bool useOutput = false; bool includeOutputs = false; bool forceRealise = false; - string bindingName; + std::string bindingName; for (auto & i : opFlags) { QueryType prev = query; @@ -637,7 +637,7 @@ static void opDump(Strings opFlags, Strings opArgs) if (opArgs.size() != 1) throw UsageError("only one argument allowed"); FdSink sink(STDOUT_FILENO); - string path = *opArgs.begin(); + std::string path = *opArgs.begin(); dumpPath(path, sink); sink.flush(); } @@ -975,9 +975,9 @@ static void opGenerateBinaryCacheKey(Strings opFlags, Strings opArgs) if (opArgs.size() != 3) throw UsageError("three arguments expected"); auto i = opArgs.begin(); - string keyName = *i++; - string secretKeyFile = *i++; - string publicKeyFile = *i++; + std::string keyName = *i++; + std::string secretKeyFile = *i++; + std::string publicKeyFile = *i++; auto secretKey = SecretKey::generate(keyName); diff --git a/src/nix/daemon.cc b/src/nix/daemon.cc index 6a40a0bd3..940923d3b 100644 --- a/src/nix/daemon.cc +++ b/src/nix/daemon.cc @@ -76,7 +76,7 @@ static void setSigChldAction(bool autoReap) } -bool matchUser(const string & user, const string & group, const Strings & users) +bool matchUser(const std::string & user, const std::string & group, const Strings & users) { if (find(users.begin(), users.end(), "*") != users.end()) return true; @@ -85,12 +85,12 @@ bool matchUser(const string & user, const string & group, const Strings & users) return true; for (auto & i : users) - if (string(i, 0, 1) == "@") { - if (group == string(i, 1)) return true; + if (i.substr(0, 1) == "@") { + if (group == i.substr(1)) return true; struct group * gr = getgrnam(i.c_str() + 1); if (!gr) continue; for (char * * mem = gr->gr_mem; *mem; mem++) - if (user == string(*mem)) return true; + if (user == std::string(*mem)) return true; } return false; @@ -198,10 +198,10 @@ static void daemonLoop() PeerInfo peer = getPeerInfo(remote.get()); struct passwd * pw = peer.uidKnown ? getpwuid(peer.uid) : 0; - string user = pw ? pw->pw_name : std::to_string(peer.uid); + std::string user = pw ? pw->pw_name : std::to_string(peer.uid); struct group * gr = peer.gidKnown ? getgrgid(peer.gid) : 0; - string group = gr ? gr->gr_name : std::to_string(peer.gid); + std::string group = gr ? gr->gr_name : std::to_string(peer.gid); Strings trustedUsers = settings.trustedUsers; Strings allowedUsers = settings.allowedUsers; @@ -212,7 +212,7 @@ static void daemonLoop() if ((!trusted && !matchUser(user, group, allowedUsers)) || group == settings.buildUsersGroup) throw Error("user '%1%' is not allowed to connect to the Nix daemon", user); - printInfo(format((string) "accepted connection from pid %1%, user %2%" + (trusted ? " (trusted)" : "")) + printInfo(format((std::string) "accepted connection from pid %1%, user %2%" + (trusted ? " (trusted)" : "")) % (peer.pidKnown ? std::to_string(peer.pid) : "") % (peer.uidKnown ? user : "")); @@ -234,7 +234,7 @@ static void daemonLoop() // For debugging, stuff the pid into argv[1]. if (peer.pidKnown && savedArgv[1]) { - string processName = std::to_string(peer.pid); + auto processName = std::to_string(peer.pid); strncpy(savedArgv[1], processName.c_str(), strlen(savedArgv[1])); } diff --git a/src/nix/hash.cc b/src/nix/hash.cc index 4535e4ab0..60d9593a7 100644 --- a/src/nix/hash.cc +++ b/src/nix/hash.cc @@ -177,7 +177,7 @@ static int compatNixHash(int argc, char * * argv) else if (*arg == "--base32") base32 = true; else if (*arg == "--truncate") truncate = true; else if (*arg == "--type") { - string s = getArg(*arg, arg, end); + std::string s = getArg(*arg, arg, end); ht = parseHashType(s); } else if (*arg == "--to-base16") op = opTo16; diff --git a/src/nix/prefetch.cc b/src/nix/prefetch.cc index 094d2a519..f2dd44ba4 100644 --- a/src/nix/prefetch.cc +++ b/src/nix/prefetch.cc @@ -16,7 +16,7 @@ using namespace nix; /* If ‘url’ starts with ‘mirror://’, then resolve it using the list of mirrors defined in Nixpkgs. */ -string resolveMirrorUrl(EvalState & state, string url) +std::string resolveMirrorUrl(EvalState & state, const std::string & url) { if (url.substr(0, 9) != "mirror://") return url; @@ -38,8 +38,8 @@ string resolveMirrorUrl(EvalState & state, string url) if (mirrorList->value->listSize() < 1) throw Error("mirror URL '%s' did not expand to anything", url); - string mirror(state.forceString(*mirrorList->value->listElems()[0])); - return mirror + (hasSuffix(mirror, "/") ? "" : "/") + string(s, p + 1); + std::string mirror(state.forceString(*mirrorList->value->listElems()[0])); + return mirror + (hasSuffix(mirror, "/") ? "" : "/") + s.substr(p + 1); } std::tuple prefetchFile( @@ -128,10 +128,10 @@ static int main_nix_prefetch_url(int argc, char * * argv) { { HashType ht = htSHA256; - std::vector args; + std::vector args; bool printPath = getEnv("PRINT_PATH") == "1"; bool fromExpr = false; - string attrPath; + std::string attrPath; bool unpack = false; bool executable = false; std::optional name; @@ -147,7 +147,7 @@ static int main_nix_prefetch_url(int argc, char * * argv) else if (*arg == "--version") printVersion("nix-prefetch-url"); else if (*arg == "--type") { - string s = getArg(*arg, arg, end); + auto s = getArg(*arg, arg, end); ht = parseHashType(s); } else if (*arg == "--print-path") @@ -186,7 +186,7 @@ static int main_nix_prefetch_url(int argc, char * * argv) /* If -A is given, get the URL from the specified Nix expression. */ - string url; + std::string url; if (!fromExpr) { if (args.empty()) throw UsageError("you must specify a URL"); diff --git a/src/nix/repl.cc b/src/nix/repl.cc index 575eb0c4c..731337004 100644 --- a/src/nix/repl.cc +++ b/src/nix/repl.cc @@ -45,7 +45,7 @@ struct NixRepl : gc #endif { - string curDir; + std::string curDir; std::unique_ptr state; Bindings * autoArgs; @@ -62,18 +62,18 @@ struct NixRepl NixRepl(const Strings & searchPath, nix::ref store); ~NixRepl(); void mainLoop(const std::vector & files); - StringSet completePrefix(string prefix); - bool getLine(string & input, const std::string &prompt); + StringSet completePrefix(const std::string & prefix); + bool getLine(std::string & input, const std::string &prompt); StorePath getDerivationPath(Value & v); - bool processLine(string line); + bool processLine(std::string line); void loadFile(const Path & path); void loadFlake(const std::string & flakeRef); void initEnv(); void reloadFiles(); void addAttrsToScope(Value & attrs); void addVarToScope(const Symbol & name, Value & v); - Expr * parseString(string s); - void evalString(string s, Value & v); + Expr * parseString(std::string s); + void evalString(std::string s, Value & v); typedef std::set ValuesSeen; std::ostream & printValue(std::ostream & str, Value & v, unsigned int maxDepth); @@ -81,11 +81,11 @@ struct NixRepl }; -string removeWhitespace(string s) +std::string removeWhitespace(std::string s) { s = chomp(s); size_t n = s.find_first_not_of(" \n\r\t"); - if (n != string::npos) s = string(s, n); + if (n != std::string::npos) s = std::string(s, n); return s; } @@ -104,7 +104,7 @@ NixRepl::~NixRepl() write_history(historyFile.c_str()); } -string runNix(Path program, const Strings & args, +std::string runNix(Path program, const Strings & args, const std::optional & input = {}) { auto subprocessEnv = getEnv(); @@ -198,7 +198,7 @@ namespace { void NixRepl::mainLoop(const std::vector & files) { - string error = ANSI_RED "error:" ANSI_NORMAL " "; + std::string error = ANSI_RED "error:" ANSI_NORMAL " "; notice("Welcome to Nix " + nixVersion + ". Type :? for help.\n"); for (auto & i : files) @@ -252,7 +252,7 @@ void NixRepl::mainLoop(const std::vector & files) } -bool NixRepl::getLine(string & input, const std::string &prompt) +bool NixRepl::getLine(std::string & input, const std::string & prompt) { struct sigaction act, old; sigset_t savedSignalMask, set; @@ -297,7 +297,7 @@ bool NixRepl::getLine(string & input, const std::string &prompt) } -StringSet NixRepl::completePrefix(string prefix) +StringSet NixRepl::completePrefix(const std::string & prefix) { StringSet completions; @@ -313,7 +313,7 @@ StringSet NixRepl::completePrefix(string prefix) size_t slash, dot; - if ((slash = cur.rfind('/')) != string::npos) { + if ((slash = cur.rfind('/')) != std::string::npos) { try { auto dir = std::string(cur, 0, slash); auto prefix2 = std::string(cur, slash + 1); @@ -323,11 +323,11 @@ StringSet NixRepl::completePrefix(string prefix) } } catch (Error &) { } - } else if ((dot = cur.rfind('.')) == string::npos) { + } else if ((dot = cur.rfind('.')) == std::string::npos) { /* This is a variable name; look it up in the current scope. */ StringSet::iterator i = varNames.lower_bound(cur); while (i != varNames.end()) { - if (string(*i, 0, cur.size()) != cur) break; + if (i->substr(0, cur.size()) != cur) break; completions.insert(prev + *i); i++; } @@ -336,8 +336,8 @@ StringSet NixRepl::completePrefix(string prefix) /* This is an expression that should evaluate to an attribute set. Evaluate it to get the names of the attributes. */ - string expr(cur, 0, dot); - string cur2 = string(cur, dot + 1); + auto expr = cur.substr(0, dot); + auto cur2 = cur.substr(dot + 1); Expr * e = parseString(expr); Value v; @@ -345,8 +345,8 @@ StringSet NixRepl::completePrefix(string prefix) state->forceAttrs(v, noPos); for (auto & i : *v.attrs) { - string name = i.name; - if (string(name, 0, cur2.size()) != cur2) continue; + std::string name = i.name; + if (name.substr(0, cur2.size()) != cur2) continue; completions.insert(prev + expr + "." + name); } @@ -365,7 +365,7 @@ StringSet NixRepl::completePrefix(string prefix) } -bool isVarName(const string & s) +static bool isVarName(std::string_view s) { if (s.size() == 0) return false; char c = s[0]; @@ -394,18 +394,18 @@ StorePath NixRepl::getDerivationPath(Value & v) { } -bool NixRepl::processLine(string line) +bool NixRepl::processLine(std::string line) { if (line == "") return true; _isInterrupted = false; - string command, arg; + std::string command, arg; if (line[0] == ':') { size_t p = line.find_first_of(" \n\r\t"); - command = string(line, 0, p); - if (p != string::npos) arg = removeWhitespace(string(line, p)); + command = line.substr(0, p); + if (p != std::string::npos) arg = removeWhitespace(line.substr(p)); } else { arg = line; } @@ -590,13 +590,13 @@ bool NixRepl::processLine(string line) else { size_t p = line.find('='); - string name; - if (p != string::npos && + std::string name; + if (p != std::string::npos && p < line.size() && line[p + 1] != '=' && - isVarName(name = removeWhitespace(string(line, 0, p)))) + isVarName(name = removeWhitespace(line.substr(0, p)))) { - Expr * e = parseString(string(line, p + 1)); + Expr * e = parseString(line.substr(p + 1)); Value & v(*state->allocValue()); v.mkThunk(env, e); addVarToScope(state->symbols.create(name), v); @@ -683,7 +683,7 @@ void NixRepl::addAttrsToScope(Value & attrs) for (auto & i : *attrs.attrs) { staticEnv.vars.emplace_back(i.name, displ); env->values[displ++] = i.value; - varNames.insert((string) i.name); + varNames.insert((std::string) i.name); } staticEnv.sort(); staticEnv.deduplicate(); @@ -700,18 +700,18 @@ void NixRepl::addVarToScope(const Symbol & name, Value & v) staticEnv.vars.emplace_back(name, displ); staticEnv.sort(); env->values[displ++] = &v; - varNames.insert((string) name); + varNames.insert((std::string) name); } -Expr * NixRepl::parseString(string s) +Expr * NixRepl::parseString(std::string s) { Expr * e = state->parseExprFromString(std::move(s), curDir, staticEnv); return e; } -void NixRepl::evalString(string s, Value & v) +void NixRepl::evalString(std::string s, Value & v) { Expr * e = parseString(s); e->eval(*state, *env, v); @@ -787,7 +787,7 @@ std::ostream & NixRepl::printValue(std::ostream & str, Value & v, unsigned int m else if (maxDepth > 0) { str << "{ "; - typedef std::map Sorted; + typedef std::map Sorted; Sorted sorted; for (auto & i : *v.attrs) sorted[i.name] = i.value; diff --git a/src/nix/why-depends.cc b/src/nix/why-depends.cc index 657df30d7..cc05deda0 100644 --- a/src/nix/why-depends.cc +++ b/src/nix/why-depends.cc @@ -157,11 +157,11 @@ struct CmdWhyDepends : SourceExprCommand closure (i.e., that have a non-infinite distance to 'dependency'). Print every edge on a path between `package` and `dependency`. */ - std::function printNode; + std::function printNode; struct BailOut { }; - printNode = [&](Node & node, const string & firstPad, const string & tailPad) { + printNode = [&](Node & node, const std::string & firstPad, const std::string & tailPad) { auto pathS = store->printStorePath(node.path); assert(node.dist != inf);