Remove std::string alias (for real this time)

Also use std::string_view in a few more places.
This commit is contained in:
Eelco Dolstra 2022-02-25 16:00:00 +01:00
parent 14b38d0887
commit df552ff53e
110 changed files with 773 additions and 681 deletions

View file

@ -240,7 +240,7 @@ SV * convertHash(char * algo, char * s, int toBase32)
PPCODE: PPCODE:
try { try {
auto h = Hash::parseAny(s, parseHashType(algo)); 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))); XPUSHs(sv_2mortal(newSVpv(s.c_str(), 0)));
} catch (Error & e) { } catch (Error & e) {
croak("%s", e.what()); croak("%s", e.what());

View file

@ -32,7 +32,7 @@ std::string escapeUri(std::string uri)
return uri; return uri;
} }
static string currentLoad; static std::string currentLoad;
static AutoCloseFD openSlotLock(const Machine & m, uint64_t slot) static AutoCloseFD openSlotLock(const Machine & m, uint64_t slot)
{ {
@ -97,7 +97,7 @@ static int main_build_remote(int argc, char * * argv)
} }
std::optional<StorePath> drvPath; std::optional<StorePath> drvPath;
string storeUri; std::string storeUri;
while (true) { while (true) {
@ -183,7 +183,7 @@ static int main_build_remote(int argc, char * * argv)
else else
{ {
// build the hint template. // build the hint template.
string errorText = std::string errorText =
"Failed to find a machine for remote build!\n" "Failed to find a machine for remote build!\n"
"derivation: %s\nrequired (system, features): (%s, %s)"; "derivation: %s\nrequired (system, features): (%s, %s)";
errorText += "\n%s available machines:"; errorText += "\n%s available machines:";
@ -193,7 +193,7 @@ static int main_build_remote(int argc, char * * argv)
errorText += "\n(%s, %s, %s, %s)"; errorText += "\n(%s, %s, %s, %s)";
// add the template values. // add the template values.
string drvstr; std::string drvstr;
if (drvPath.has_value()) if (drvPath.has_value())
drvstr = drvPath->to_string(); drvstr = drvPath->to_string();
else else
@ -208,7 +208,7 @@ static int main_build_remote(int argc, char * * argv)
for (auto & m : machines) for (auto & m : machines)
error error
% concatStringsSep<std::vector<string>>(", ", m.systemTypes) % concatStringsSep<std::vector<std::string>>(", ", m.systemTypes)
% m.maxJobs % m.maxJobs
% concatStringsSep<StringSet>(", ", m.supportedFeatures) % concatStringsSep<StringSet>(", ", m.supportedFeatures)
% concatStringsSep<StringSet>(", ", m.mandatoryFeatures); % concatStringsSep<StringSet>(", ", m.mandatoryFeatures);

View file

@ -9,7 +9,7 @@ namespace nix {
static Strings parseAttrPath(std::string_view s) static Strings parseAttrPath(std::string_view s)
{ {
Strings res; Strings res;
string cur; std::string cur;
auto i = s.begin(); auto i = s.begin();
while (i != s.end()) { while (i != s.end()) {
if (*i == '.') { if (*i == '.') {
@ -41,7 +41,7 @@ std::vector<Symbol> parseAttrPath(EvalState & state, std::string_view s)
} }
std::pair<Value *, Pos> findAlongAttrPath(EvalState & state, const string & attrPath, std::pair<Value *, Pos> findAlongAttrPath(EvalState & state, const std::string & attrPath,
Bindings & autoArgs, Value & vIn) Bindings & autoArgs, Value & vIn)
{ {
Strings tokens = parseAttrPath(attrPath); Strings tokens = parseAttrPath(attrPath);
@ -121,7 +121,7 @@ Pos findPackageFilename(EvalState & state, Value & v, std::string what)
std::string filename(pos, 0, colon); std::string filename(pos, 0, colon);
unsigned int lineno; unsigned int lineno;
try { 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) { } catch (std::invalid_argument & e) {
throw ParseError("cannot parse line number '%s'", pos); throw ParseError("cannot parse line number '%s'", pos);
} }

View file

@ -10,8 +10,11 @@ namespace nix {
MakeError(AttrPathNotFound, Error); MakeError(AttrPathNotFound, Error);
MakeError(NoPositionInfo, Error); MakeError(NoPositionInfo, Error);
std::pair<Value *, Pos> findAlongAttrPath(EvalState & state, const string & attrPath, std::pair<Value *, Pos> findAlongAttrPath(
Bindings & autoArgs, Value & vIn); EvalState & state,
const std::string & attrPath,
Bindings & autoArgs,
Value & vIn);
/* Heuristic to find the filename and lineno or a nix value. */ /* Heuristic to find the filename and lineno or a nix value. */
Pos findPackageFilename(EvalState & state, Value & v, std::string what); Pos findPackageFilename(EvalState & state, Value & v, std::string what);

View file

@ -105,7 +105,7 @@ public:
for (size_t n = 0; n < size_; n++) for (size_t n = 0; n < size_; n++)
res.emplace_back(&attrs[n]); res.emplace_back(&attrs[n]);
std::sort(res.begin(), res.end(), [](const Attr * a, const Attr * b) { 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; return res;
} }

View file

@ -77,7 +77,7 @@ Bindings * MixEvalArgs::getAutoArgs(EvalState & state)
for (auto & i : autoArgs) { for (auto & i : autoArgs) {
auto v = state.allocValue(); auto v = state.allocValue();
if (i.second[0] == 'E') 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 else
v->mkString(((std::string_view) i.second).substr(1)); v->mkString(((std::string_view) i.second).substr(1));
res.insert(state.symbols.create(i.first), v); res.insert(state.symbols.create(i.first), v);
@ -85,17 +85,17 @@ Bindings * MixEvalArgs::getAutoArgs(EvalState & state)
return res.finish(); return res.finish();
} }
Path lookupFileArg(EvalState & state, string s) Path lookupFileArg(EvalState & state, std::string_view s)
{ {
if (isUri(s)) { if (isUri(s)) {
return state.store->toRealPath( return state.store->toRealPath(
fetchers::downloadTarball( fetchers::downloadTarball(
state.store, resolveUri(s), "source", false).first.storePath); state.store, resolveUri(s), "source", false).first.storePath);
} else if (s.size() > 2 && s.at(0) == '<' && s.at(s.size() - 1) == '>') { } 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); return state.findFile(p);
} else } else
return absPath(s); return absPath(std::string(s));
} }
} }

View file

@ -22,6 +22,6 @@ private:
std::map<std::string, std::string> autoArgs; std::map<std::string, std::string> autoArgs;
}; };
Path lookupFileArg(EvalState & state, string s); Path lookupFileArg(EvalState & state, std::string_view s);
} }

View file

@ -596,7 +596,7 @@ std::vector<Symbol> AttrCursor::getAttrs()
for (auto & attr : *getValue().attrs) for (auto & attr : *getValue().attrs)
attrs.push_back(attr.name); attrs.push_back(attr.name);
std::sort(attrs.begin(), attrs.end(), [](const Symbol & a, const Symbol & b) { 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) if (root->db)

View file

@ -183,7 +183,7 @@ const Value *getPrimOp(const Value &v) {
return primOp; return primOp;
} }
string showType(ValueType type) std::string_view showType(ValueType type)
{ {
switch (type) { switch (type) {
case nInt: return "an integer"; 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) { switch (v.internalType) {
case tString: return v.string.context ? "a string with context" : "a string"; case tString: return v.string.context ? "a string with context" : "a string";
case tPrimOp: 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: 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 tExternal: return v.external->showType();
case tThunk: return "a thunk"; case tThunk: return "a thunk";
case tApp: return "a function application"; case tApp: return "a function application";
case tBlackhole: return "a black hole"; case tBlackhole: return "a black hole";
default: 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 /* Very hacky way to parse $NIX_PATH, which is colon-separated, but
can contain URLs (e.g. "nixpkgs=https://bla...:foo=https://"). */ 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; 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(); Value * v2 = allocValue();
*v2 = v; *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); staticBaseEnv.vars.emplace_back(symbols.create(name), baseEnvDispl);
baseEnv.values[baseEnvDispl++] = v; 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)); 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) 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); Symbol sym = symbols.create(name2);
/* Hack to make constants lazy: turn them into a application of /* 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; return *baseEnv.values[0]->attrs->find(symbols.create(name))->value;
} }
@ -703,12 +703,12 @@ std::optional<EvalState::Doc> EvalState::getDoc(Value & v)
evaluator. So here are some helper functions for throwing evaluator. So here are some helper functions for throwing
exceptions. */ exceptions. */
LocalNoInlineNoReturn(void throwEvalError(const char * s, const string & s2)) LocalNoInlineNoReturn(void throwEvalError(const char * s, const std::string & s2))
{ {
throw EvalError(s, 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({ throw EvalError({
.msg = hintfmt(s, s2), .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); 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({ throw EvalError({
.msg = hintfmt(s, s2, s3), .msg = hintfmt(s, s2, s3),
@ -759,7 +759,7 @@ LocalNoInlineNoReturn(void throwTypeError(const char * s, const Value & v))
throw TypeError(s, showType(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({ throw AssertionError({
.msg = hintfmt(s, s1), .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({ throw UndefinedVarError({
.msg = hintfmt(s, s1), .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({ throw MissingArgumentError({
.msg = hintfmt(s, s1), .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); 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); 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; std::ostringstream out;
bool first = true; bool first = true;
@ -1395,7 +1395,7 @@ void EvalState::callFunction(Value & fun, size_t nrArgs, Value * * args, Value &
if (loggerSettings.showTrace.get()) { if (loggerSettings.showTrace.get()) {
addErrorTrace(e, lambda.pos, "while evaluating %s", addErrorTrace(e, lambda.pos, "while evaluating %s",
(lambda.name.set() (lambda.name.set()
? "'" + (string) lambda.name + "'" ? "'" + (const std::string &) lambda.name + "'"
: "anonymous lambda")); : "anonymous lambda"));
addErrorTrace(e, pos, "from call site%s", ""); 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 !<name>!<path> into a pair <path, /* Decode a context string !<name>!<path> into a pair <path,
name>. */ name>. */
std::pair<string, string> decodeContext(std::string_view s) std::pair<std::string, std::string> decodeContext(std::string_view s)
{ {
if (s.at(0) == '!') { if (s.at(0) == '!') {
size_t index = s.find("!", 1); size_t index = s.find("!", 1);
@ -1946,7 +1946,7 @@ bool EvalState::isDerivation(Value & v)
} }
std::optional<string> EvalState::tryAttrsToString(const Pos & pos, Value & v, std::optional<std::string> EvalState::tryAttrsToString(const Pos & pos, Value & v,
PathSet & context, bool coerceMore, bool copyToStore) PathSet & context, bool coerceMore, bool copyToStore)
{ {
auto i = v.attrs->find(sToString); 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.type() == nNull) return "";
if (v.isList()) { if (v.isList()) {
string result; std::string result;
for (auto [n, v2] : enumerate(v.listItems())) { for (auto [n, v2] : enumerate(v.listItems())) {
result += *coerceToString(pos, *v2, context, coerceMore, copyToStore); result += *coerceToString(pos, *v2, context, coerceMore, copyToStore);
if (n < v.listSize() - 1 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)) if (nix::isDerivation(path))
throwEvalError("file names are not allowed to end in '%1%'", drvExtension); 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) 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] != '/') if (path == "" || path[0] != '/')
throwEvalError(pos, "string '%1%' doesn't represent an absolute path", path); throwEvalError(pos, "string '%1%' doesn't represent an absolute path", path);
return path; return path;
@ -2213,11 +2213,11 @@ void EvalState::printStats()
for (auto & i : functionCalls) { for (auto & i : functionCalls) {
auto obj = list.object(); auto obj = list.object();
if (i.first->name.set()) if (i.first->name.set())
obj.attr("name", (const string &) i.first->name); obj.attr("name", (const std::string &) i.first->name);
else else
obj.attr("name", nullptr); obj.attr("name", nullptr);
if (i.first->pos) { 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("line", i.first->pos.line);
obj.attr("column", i.first->pos.column); obj.attr("column", i.first->pos.column);
} }
@ -2229,7 +2229,7 @@ void EvalState::printStats()
for (auto & i : attrSelects) { for (auto & i : attrSelects) {
auto obj = list.object(); auto obj = list.object();
if (i.first) { 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("line", i.first.line);
obj.attr("column", i.first.column); 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({ throw TypeError({
.msg = hintfmt("cannot coerce %1% to a string", showType()), .msg = hintfmt("cannot coerce %1% to a string", showType()),

View file

@ -150,7 +150,7 @@ public:
const Pos & pos const Pos & pos
); );
void addToSearchPath(const string & s); void addToSearchPath(const std::string & s);
SearchPath getSearchPath() { return searchPath; } SearchPath getSearchPath() { return searchPath; }
@ -251,7 +251,7 @@ public:
set with attribute `type = "derivation"'). */ set with attribute `type = "derivation"'). */
bool isDerivation(Value & v); bool isDerivation(Value & v);
std::optional<string> tryAttrsToString(const Pos & pos, Value & v, std::optional<std::string> tryAttrsToString(const Pos & pos, Value & v,
PathSet & context, bool coerceMore = false, bool copyToStore = true); PathSet & context, bool coerceMore = false, bool copyToStore = true);
/* String coercion. Converts strings, paths and derivations to a /* String coercion. Converts strings, paths and derivations to a
@ -262,7 +262,7 @@ public:
bool coerceMore = false, bool copyToStore = true, bool coerceMore = false, bool copyToStore = true,
bool canonicalizePath = 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 coercion. Converts strings, paths and derivations to a
path. The result is guaranteed to be a canonicalised, absolute path. The result is guaranteed to be a canonicalised, absolute
@ -284,18 +284,18 @@ private:
void createBaseEnv(); 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); size_t arity, PrimOpFun primOp);
Value * addPrimOp(PrimOp && primOp); Value * addPrimOp(PrimOp && primOp);
public: public:
Value & getBuiltin(const string & name); Value & getBuiltin(const std::string & name);
struct Doc struct Doc
{ {
@ -414,12 +414,12 @@ private:
/* Return a string representing the type of the value `v'. */ /* Return a string representing the type of the value `v'. */
string showType(ValueType type); std::string_view showType(ValueType type);
string showType(const Value & v); std::string showType(const Value & v);
/* Decode a context string !<name>!<path> into a pair <path, /* Decode a context string !<name>!<path> into a pair <path,
name>. */ name>. */
std::pair<string, string> decodeContext(std::string_view s); std::pair<std::string, std::string> decodeContext(std::string_view s);
/* If `path' refers to a directory, then append "/default.nix". */ /* If `path' refers to a directory, then append "/default.nix". */
Path resolveExprPath(Path path); Path resolveExprPath(Path path);

View file

@ -254,7 +254,7 @@ static Flake getFlake(
for (auto & setting : *nixConfig->value->attrs) { for (auto & setting : *nixConfig->value->attrs) {
forceTrivialValue(state, *setting.value, *setting.pos); forceTrivialValue(state, *setting.value, *setting.pos);
if (setting.value->type() == nString) 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) { else if (setting.value->type() == nPath) {
PathSet emptyContext = {}; PathSet emptyContext = {};
flake.config.settings.emplace( 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); 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); auto flakeRef = parseFlakeRef(flakeRefS, {}, true);
if (evalSettings.pureEval && !flakeRef.input.isLocked()) if (evalSettings.pureEval && !flakeRef.input.isLocked())
throw Error("cannot call 'getFlake' on unlocked flake reference '%s', at %s (use --impure to override)", flakeRefS, pos); throw Error("cannot call 'getFlake' on unlocked flake reference '%s', at %s (use --impure to override)", flakeRefS, pos);

View file

@ -11,8 +11,8 @@
namespace nix { namespace nix {
DrvInfo::DrvInfo(EvalState & state, const string & attrPath, Bindings * attrs) DrvInfo::DrvInfo(EvalState & state, std::string attrPath, Bindings * attrs)
: state(&state), attrs(attrs), attrPath(attrPath) : state(&state), attrs(attrs), attrPath(std::move(attrPath))
{ {
} }
@ -47,7 +47,7 @@ DrvInfo::DrvInfo(EvalState & state, ref<Store> store, const std::string & drvPat
} }
string DrvInfo::queryName() const std::string DrvInfo::queryName() const
{ {
if (name == "" && attrs) { if (name == "" && attrs) {
auto i = attrs->find(state->sName); 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) { if (system == "" && attrs) {
auto i = attrs->find(state->sSystem); 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) { if (drvPath == "" && attrs) {
Bindings::iterator i = attrs->find(state->sDrvPath); 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) { if (!outPath && attrs) {
Bindings::iterator i = attrs->find(state->sOutPath); Bindings::iterator i = attrs->find(state->sOutPath);
@ -104,7 +104,7 @@ DrvInfo::Outputs DrvInfo::queryOutputs(bool onlyOutputsToInstall)
/* For each output... */ /* For each output... */
for (auto elem : i->value->listItems()) { for (auto elem : i->value->listItems()) {
/* Evaluate the corresponding set. */ /* 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)); Bindings::iterator out = attrs->find(state->symbols.create(name));
if (out == attrs->end()) continue; // FIXME: throw error? if (out == attrs->end()) continue; // FIXME: throw error?
state->forceAttrs(*out->value, *i->pos); 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) { if (outputName == "" && attrs) {
Bindings::iterator i = attrs->find(state->sOutputName); 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; if (!getMeta()) return 0;
Bindings::iterator a = meta->find(state->symbols.create(name)); 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); Value * v = queryMeta(name);
if (!v || v->type() != nString) return ""; 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); Value * v = queryMeta(name);
if (!v) return def; if (!v) return def;
@ -221,7 +221,7 @@ NixInt DrvInfo::queryMetaInt(const string & name, NixInt def)
return def; return def;
} }
NixFloat DrvInfo::queryMetaFloat(const string & name, NixFloat def) NixFloat DrvInfo::queryMetaFloat(const std::string & name, NixFloat def)
{ {
Value * v = queryMeta(name); Value * v = queryMeta(name);
if (!v) return def; 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); Value * v = queryMeta(name);
if (!v) return def; 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(); getMeta();
auto attrs = state->buildBindings(1 + (meta ? meta->size() : 0)); auto attrs = state->buildBindings(1 + (meta ? meta->size() : 0));
@ -274,7 +274,7 @@ typedef std::set<Bindings *> Done;
The result boolean indicates whether it makes sense The result boolean indicates whether it makes sense
for the caller to recursively search for derivations in `v'. */ for the caller to recursively search for derivations in `v'. */
static bool getDerivation(EvalState & state, Value & 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) bool ignoreAssertionFailures)
{ {
try { try {
@ -311,7 +311,7 @@ std::optional<DrvInfo> 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; 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, static void getDerivations(EvalState & state, Value & vIn,
const string & pathPrefix, Bindings & autoArgs, const std::string & pathPrefix, Bindings & autoArgs,
DrvInfos & drvs, Done & done, DrvInfos & drvs, Done & done,
bool ignoreAssertionFailures) bool ignoreAssertionFailures)
{ {
@ -346,7 +346,7 @@ static void getDerivations(EvalState & state, Value & vIn,
debug("evaluating attribute '%1%'", i->name); debug("evaluating attribute '%1%'", i->name);
if (!std::regex_match(std::string(i->name), attrRegex)) if (!std::regex_match(std::string(i->name), attrRegex))
continue; continue;
string pathPrefix2 = addToPath(pathPrefix, i->name); std::string pathPrefix2 = addToPath(pathPrefix, i->name);
if (combineChannels) if (combineChannels)
getDerivations(state, *i->value, pathPrefix2, autoArgs, drvs, done, ignoreAssertionFailures); getDerivations(state, *i->value, pathPrefix2, autoArgs, drvs, done, ignoreAssertionFailures);
else if (getDerivation(state, *i->value, pathPrefix2, 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) { else if (v.type() == nList) {
for (auto [n, elem] : enumerate(v.listItems())) { 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)) if (getDerivation(state, *elem, pathPrefix2, drvs, done, ignoreAssertionFailures))
getDerivations(state, *elem, pathPrefix2, autoArgs, 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) Bindings & autoArgs, DrvInfos & drvs, bool ignoreAssertionFailures)
{ {
Done done; Done done;

View file

@ -12,16 +12,16 @@ namespace nix {
struct DrvInfo struct DrvInfo
{ {
public: public:
typedef std::map<string, Path> Outputs; typedef std::map<std::string, Path> Outputs;
private: private:
EvalState * state; EvalState * state;
mutable string name; mutable std::string name;
mutable string system; mutable std::string system;
mutable string drvPath; mutable std::string drvPath;
mutable std::optional<string> outPath; mutable std::optional<std::string> outPath;
mutable string outputName; mutable std::string outputName;
Outputs outputs; Outputs outputs;
bool failed = false; // set if we get an AssertionError bool failed = false; // set if we get an AssertionError
@ -33,36 +33,36 @@ private:
bool checkMeta(Value & v); bool checkMeta(Value & v);
public: public:
string attrPath; /* path towards the derivation */ std::string attrPath; /* path towards the derivation */
DrvInfo(EvalState & state) : state(&state) { }; 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> store, const std::string & drvPathWithOutputs); DrvInfo(EvalState & state, ref<Store> store, const std::string & drvPathWithOutputs);
string queryName() const; std::string queryName() const;
string querySystem() const; std::string querySystem() const;
string queryDrvPath() const; std::string queryDrvPath() const;
string queryOutPath() const; std::string queryOutPath() const;
string queryOutputName() const; std::string queryOutputName() const;
/** Return the list of outputs. The "outputs to install" are determined by `meta.outputsToInstall`. */ /** Return the list of outputs. The "outputs to install" are determined by `meta.outputsToInstall`. */
Outputs queryOutputs(bool onlyOutputsToInstall = false); Outputs queryOutputs(bool onlyOutputsToInstall = false);
StringSet queryMetaNames(); StringSet queryMetaNames();
Value * queryMeta(const string & name); Value * queryMeta(const std::string & name);
string queryMetaString(const string & name); std::string queryMetaString(const std::string & name);
NixInt queryMetaInt(const string & name, NixInt def); NixInt queryMetaInt(const std::string & name, NixInt def);
NixFloat queryMetaFloat(const string & name, NixFloat def); NixFloat queryMetaFloat(const std::string & name, NixFloat def);
bool queryMetaBool(const string & name, bool def); bool queryMetaBool(const std::string & name, bool def);
void setMeta(const string & name, Value * v); void setMeta(const std::string & name, Value * v);
/* /*
MetaInfo queryMetaInfo(EvalState & state) const; MetaInfo queryMetaInfo(EvalState & state) const;
MetaValue queryMetaInfo(EvalState & state, const string & name) const; MetaValue queryMetaInfo(EvalState & state, const string & name) const;
*/ */
void setName(const string & s) { name = s; } void setName(const std::string & s) { name = s; }
void setDrvPath(const string & s) { drvPath = s; } void setDrvPath(const std::string & s) { drvPath = s; }
void setOutPath(const string & s) { outPath = s; } void setOutPath(const std::string & s) { outPath = s; }
void setFailed() { failed = true; }; void setFailed() { failed = true; };
bool hasFailed() { return failed; }; bool hasFailed() { return failed; };
@ -81,7 +81,7 @@ typedef std::list<DrvInfo> DrvInfos;
std::optional<DrvInfo> getDerivation(EvalState & state, std::optional<DrvInfo> getDerivation(EvalState & state,
Value & v, bool ignoreAssertionFailures); 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, Bindings & autoArgs, DrvInfos & drvs,
bool ignoreAssertionFailures); bool ignoreAssertionFailures);

View file

@ -16,10 +16,10 @@ std::ostream & operator << (std::ostream & str, const Expr & e)
return str; return str;
} }
static void showString(std::ostream & str, const string & s) static void showString(std::ostream & str, std::string_view s)
{ {
str << '"'; str << '"';
for (auto c : (string) s) for (auto c : s)
if (c == '"' || c == '\\' || c == '$') str << "\\" << c; if (c == '"' || c == '\\' || c == '$') str << "\\" << c;
else if (c == '\n') str << "\\n"; else if (c == '\n') str << "\\n";
else if (c == '\r') str << "\\r"; else if (c == '\r') str << "\\r";
@ -28,7 +28,7 @@ static void showString(std::ostream & str, const string & s)
str << '"'; str << '"';
} }
static void showId(std::ostream & str, const string & s) static void showId(std::ostream & str, std::string_view s)
{ {
if (s.empty()) if (s.empty())
str << "\"\""; str << "\"\"";
@ -218,7 +218,7 @@ std::ostream & operator << (std::ostream & str, const Pos & pos)
auto f = format(ANSI_BOLD "%1%" ANSI_NORMAL ":%2%:%3%"); auto f = format(ANSI_BOLD "%1%" ANSI_NORMAL ":%2%:%3%");
switch (pos.origin) { switch (pos.origin) {
case foFile: case foFile:
f % (string) pos.file; f % (const std::string &) pos.file;
break; break;
case foStdin: case foStdin:
case foString: 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; std::ostringstream out;
bool first = true; 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);
} }

View file

@ -26,18 +26,21 @@ struct Pos
FileOrigin origin; FileOrigin origin;
Symbol file; Symbol file;
unsigned int line, column; 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) 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 operator bool() const
{ {
return line != 0; return line != 0;
} }
bool operator < (const Pos & p2) const bool operator < (const Pos & p2) const
{ {
if (!line) return p2.line; if (!line) return p2.line;
if (!p2.line) return false; 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 true;
if (d > 0) return false; if (d > 0) return false;
if (line < p2.line) return true; if (line < p2.line) return true;
@ -68,7 +71,7 @@ struct AttrName
typedef std::vector<AttrName> AttrPath; typedef std::vector<AttrName> AttrPath;
string showAttrPath(const AttrPath & attrPath); std::string showAttrPath(const AttrPath & attrPath);
/* Abstract syntax of Nix expressions. */ /* Abstract syntax of Nix expressions. */
@ -110,7 +113,7 @@ struct ExprFloat : Expr
struct ExprString : Expr struct ExprString : Expr
{ {
string s; std::string s;
Value v; Value v;
ExprString(std::string s) : s(std::move(s)) { v.mkString(this->s.data()); }; ExprString(std::string s) : s(std::move(s)) { v.mkString(this->s.data()); };
COMMON_METHODS COMMON_METHODS
@ -119,9 +122,9 @@ struct ExprString : Expr
struct ExprPath : Expr struct ExprPath : Expr
{ {
string s; std::string s;
Value v; 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 COMMON_METHODS
Value * maybeThunk(EvalState & state, Env & env); Value * maybeThunk(EvalState & state, Env & env);
}; };
@ -249,7 +252,7 @@ struct ExprLambda : Expr
{ {
}; };
void setName(Symbol & name); void setName(Symbol & name);
string showNamePos() const; std::string showNamePos() const;
inline bool hasFormals() const { return formals != nullptr; } inline bool hasFormals() const { return formals != nullptr; }
COMMON_METHODS COMMON_METHODS
}; };

View file

@ -244,7 +244,7 @@ static Expr * stripIndentation(const Pos & pos, SymbolTable & symbols,
es2->emplace_back(i->first, e); es2->emplace_back(i->first, e);
}; };
const auto trimString = [&] (const StringToken & t) { const auto trimString = [&] (const StringToken & t) {
string s2; std::string s2;
for (size_t j = 0; j < t.l; ++j) { for (size_t j = 0; j < t.l; ++j) {
if (atStartOfLine) { if (atStartOfLine) {
if (t.p[j] == ' ') { 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 /* Remove the last line if it is empty and consists only of
spaces. */ spaces. */
if (n == 1) { if (n == 1) {
string::size_type p = s2.find_last_of('\n'); std::string::size_type p = s2.find_last_of('\n');
if (p != string::npos && s2.find_first_not_of(' ', p + 1) == string::npos) if (p != std::string::npos && s2.find_first_not_of(' ', p + 1) == std::string::npos)
s2 = string(s2, 0, p + 1); s2 = std::string(s2, 0, p + 1);
} }
es2->emplace_back(i->first, new ExprString(s2)); es2->emplace_back(i->first, new ExprString(s2));
@ -466,7 +466,7 @@ expr_simple
$$ = new ExprConcatStrings(CUR_POS, false, $2); $$ = new ExprConcatStrings(CUR_POS, false, $2);
} }
| SPATH { | SPATH {
string path($1.p + 1, $1.l - 2); std::string path($1.p + 1, $1.l - 2);
$$ = new ExprCall(CUR_POS, $$ = new ExprCall(CUR_POS,
new ExprVar(data->symbols.create("__findFile")), new ExprVar(data->symbols.create("__findFile")),
{new ExprVar(data->symbols.create("__nixPath")), {new ExprVar(data->symbols.create("__nixPath")),
@ -479,7 +479,7 @@ expr_simple
.msg = hintfmt("URL literals are disabled"), .msg = hintfmt("URL literals are disabled"),
.errPos = CUR_POS .errPos = CUR_POS
}); });
$$ = new ExprString(string($1)); $$ = new ExprString(std::string($1));
} }
| '(' expr ')' { $$ = $2; } | '(' expr ')' { $$ = $2; }
/* Let expressions `let {..., body = ...}' are just desugared /* Let expressions `let {..., body = ...}' are just desugared
@ -494,19 +494,19 @@ expr_simple
; ;
string_parts string_parts
: STR { $$ = new ExprString(string($1)); } : STR { $$ = new ExprString(std::string($1)); }
| string_parts_interpolated { $$ = new ExprConcatStrings(CUR_POS, true, $1); } | string_parts_interpolated { $$ = new ExprConcatStrings(CUR_POS, true, $1); }
| { $$ = new ExprString(""); } | { $$ = new ExprString(""); }
; ;
string_parts_interpolated string_parts_interpolated
: string_parts_interpolated STR : 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); } | string_parts_interpolated DOLLAR_CURLY expr '}' { $$ = $1; $1->emplace_back(makeCurPos(@2, data), $3); }
| DOLLAR_CURLY expr '}' { $$ = new std::vector<std::pair<Pos, Expr *> >; $$->emplace_back(makeCurPos(@1, data), $2); } | DOLLAR_CURLY expr '}' { $$ = new std::vector<std::pair<Pos, Expr *> >; $$->emplace_back(makeCurPos(@1, data), $2); }
| STR DOLLAR_CURLY expr '}' { | STR DOLLAR_CURLY expr '}' {
$$ = new std::vector<std::pair<Pos, Expr *> >; $$ = new std::vector<std::pair<Pos, Expr *> >;
$$->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); $$->emplace_back(makeCurPos(@2, data), $3);
} }
; ;
@ -520,7 +520,7 @@ path_start
$$ = new ExprPath(path); $$ = new ExprPath(path);
} }
| HPATH { | 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); $$ = 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('='); size_t pos = s.find('=');
string prefix; std::string prefix;
Path path; Path path;
if (pos == string::npos) { if (pos == std::string::npos) {
path = s; path = s;
} else { } else {
prefix = string(s, 0, pos); prefix = std::string(s, 0, pos);
path = string(s, pos + 1); path = std::string(s, pos + 1);
} }
searchPath.emplace_back(prefix, path); searchPath.emplace_back(prefix, path);

View file

@ -141,7 +141,7 @@ static void mkOutputString(
BindingsBuilder & attrs, BindingsBuilder & attrs,
const StorePath & drvPath, const StorePath & drvPath,
const BasicDerivation & drv, const BasicDerivation & drv,
const std::pair<string, DerivationOutput> & o) const std::pair<std::string, DerivationOutput> & o)
{ {
auto optOutputPath = o.second.path(*state.store, drv.name, o.first); auto optOutputPath = o.second.path(*state.store, drv.name, o.first);
attrs.alloc(o.first).mkString( 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]); 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); void *handle = dlopen(path.c_str(), RTLD_LAZY | RTLD_LOCAL);
if (!handle) 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) static void prim_typeOf(EvalState & state, const Pos & pos, Value * * args, Value & v)
{ {
state.forceValue(*args[0], pos); state.forceValue(*args[0], pos);
string t; std::string t;
switch (args[0]->type()) { switch (args[0]->type()) {
case nInt: t = "int"; break; case nInt: t = "int"; break;
case nBool: t = "bool"; break; case nBool: t = "bool"; break;
@ -707,7 +707,7 @@ static RegisterPrimOp primop_abort({
.fun = [](EvalState & state, const Pos & pos, Value * * args, Value & v) .fun = [](EvalState & state, const Pos & pos, Value * * args, Value & v)
{ {
PathSet context; 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); 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) .fun = [](EvalState & state, const Pos & pos, Value * * args, Value & v)
{ {
PathSet context; PathSet context;
string s = state.coerceToString(pos, *args[0], context).toOwned(); auto s = state.coerceToString(pos, *args[0], context).toOwned();
throw ThrownError(s); throw ThrownError(s);
} }
}); });
@ -826,7 +826,7 @@ static RegisterPrimOp primop_tryEval({
/* Return an environment variable. Use with care. */ /* Return an environment variable. Use with care. */
static void prim_getEnv(EvalState & state, const Pos & pos, Value * * args, Value & v) 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("")); 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 pos
); );
string drvName; std::string drvName;
Pos & posDrvName(*attr->pos); Pos & posDrvName(*attr->pos);
try { try {
drvName = state.forceStringNoCtx(*attr->value, pos); 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()) { for (auto & i : args[0]->attrs->lexicographicOrder()) {
if (i->name == state.sIgnoreNulls) continue; if (i->name == state.sIgnoreNulls) continue;
const string & key = i->name; const std::string & key = i->name;
vomit("processing attribute '%1%'", key); vomit("processing attribute '%1%'", key);
auto handleHashMode = [&](const std::string_view s) { 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) { else if (i->name == state.sArgs) {
state.forceList(*i->value, pos); state.forceList(*i->value, pos);
for (auto elem : i->value->listItems()) { 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); 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 !<name>!<path>. */ /* Handle derivation outputs of the form !<name>!<path>. */
else if (path.at(0) == '!') { else if (path.at(0) == '!') {
std::pair<string, string> ctx = decodeContext(path); auto ctx = decodeContext(path);
drv.inputDrvs[state.store->parseStorePath(ctx.first)].insert(ctx.second); 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) static void prim_readFile(EvalState & state, const Pos & pos, Value * * args, Value & v)
{ {
auto path = realisePath(state, pos, *args[0]); auto path = realisePath(state, pos, *args[0]);
string s = readFile(path); auto s = readFile(path);
if (s.find((char) 0) != string::npos) if (s.find((char) 0) != std::string::npos)
throw Error("the contents of the file '%1%' cannot be represented as a Nix string", path); throw Error("the contents of the file '%1%' cannot be represented as a Nix string", path);
StorePathSet refs; StorePathSet refs;
if (state.store->isInStore(path)) { 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()) { for (auto v2 : args[0]->listItems()) {
state.forceAttrs(*v2, pos); state.forceAttrs(*v2, pos);
string prefix; std::string prefix;
Bindings::iterator i = v2->attrs->find(state.sPrefix); Bindings::iterator i = v2->attrs->find(state.sPrefix);
if (i != v2->attrs->end()) if (i != v2->attrs->end())
prefix = state.forceStringNoCtx(*i->value, pos); prefix = state.forceStringNoCtx(*i->value, pos);
@ -1488,7 +1488,7 @@ static void prim_findFile(EvalState & state, const Pos & pos, Value * * args, Va
); );
PathSet context; 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 { try {
auto rewrites = state.realiseContext(context); 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) static void prim_toFile(EvalState & state, const Pos & pos, Value * * args, Value & v)
{ {
PathSet context; PathSet context;
string name(state.forceStringNoCtx(*args[0], pos)); std::string name(state.forceStringNoCtx(*args[0], pos));
string contents(state.forceString(*args[1], context, pos)); std::string contents(state.forceString(*args[1], context, pos));
StorePathSet refs; StorePathSet refs;
@ -1863,7 +1863,7 @@ static RegisterPrimOp primop_toFile({
static void addPath( static void addPath(
EvalState & state, EvalState & state,
const Pos & pos, const Pos & pos,
const string & name, const std::string & name,
Path path, Path path,
Value * filterFun, Value * filterFun,
FileIngestionMethod method, FileIngestionMethod method,
@ -2016,14 +2016,14 @@ static void prim_path(EvalState & state, const Pos & pos, Value * * args, Value
{ {
state.forceAttrs(*args[0], pos); state.forceAttrs(*args[0], pos);
Path path; Path path;
string name; std::string name;
Value * filterFun = nullptr; Value * filterFun = nullptr;
auto method = FileIngestionMethod::Recursive; auto method = FileIngestionMethod::Recursive;
std::optional<Hash> expectedHash; std::optional<Hash> expectedHash;
PathSet context; PathSet context;
for (auto & attr : *args[0]->attrs) { for (auto & attr : *args[0]->attrs) {
const string & n(attr.name); auto & n(attr.name);
if (n == "path") if (n == "path")
path = state.coerceToPath(*attr.pos, *attr.value, context); path = state.coerceToPath(*attr.pos, *attr.value, context);
else if (attr.name == state.sName) 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); auto sep = state.forceString(*args[0], context, pos);
state.forceList(*args[1], pos); state.forceList(*args[1], pos);
string res; std::string res;
res.reserve((args[1]->listSize() + 32) * sep.size()); res.reserve((args[1]->listSize() + 32) * sep.size());
bool first = true; bool first = true;
@ -3649,12 +3649,12 @@ static void prim_replaceStrings(EvalState & state, const Pos & pos, Value * * ar
.errPos = pos .errPos = pos
}); });
std::vector<string> from; std::vector<std::string> from;
from.reserve(args[0]->listSize()); from.reserve(args[0]->listSize());
for (auto elem : args[0]->listItems()) for (auto elem : args[0]->listItems())
from.emplace_back(state.forceString(*elem, pos)); from.emplace_back(state.forceString(*elem, pos));
std::vector<std::pair<string, PathSet>> to; std::vector<std::pair<std::string, PathSet>> to;
to.reserve(args[1]->listSize()); to.reserve(args[1]->listSize());
for (auto elem : args[1]->listItems()) { for (auto elem : args[1]->listItems()) {
PathSet ctx; PathSet ctx;
@ -3665,7 +3665,7 @@ static void prim_replaceStrings(EvalState & state, const Pos & pos, Value * * ar
PathSet context; PathSet context;
auto s = state.forceString(*args[2], context, pos); 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. // Loops one past last character to handle the case where 'from' contains an empty string.
for (size_t p = 0; p <= s.size(); ) { for (size_t p = 0; p <= s.size(); ) {
bool found = false; bool found = false;

View file

@ -37,7 +37,7 @@ static void prim_unsafeDiscardOutputDependency(EvalState & state, const Pos & po
PathSet context2; PathSet context2;
for (auto & p : context) 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); v.mkString(*s, context2);
} }
@ -76,13 +76,13 @@ static void prim_getContext(EvalState & state, const Pos & pos, Value * * args,
auto contextInfos = std::map<Path, ContextInfo>(); auto contextInfos = std::map<Path, ContextInfo>();
for (const auto & p : context) { for (const auto & p : context) {
Path drv; Path drv;
string output; std::string output;
const Path * path = &p; const Path * path = &p;
if (p.at(0) == '=') { if (p.at(0) == '=') {
drv = string(p, 1); drv = std::string(p, 1);
path = &drv; path = &drv;
} else if (p.at(0) == '!') { } else if (p.at(0) == '!') {
std::pair<string, string> ctx = decodeContext(p); std::pair<std::string, std::string> ctx = decodeContext(p);
drv = ctx.first; drv = ctx.first;
output = ctx.second; output = ctx.second;
path = &drv; path = &drv;
@ -166,7 +166,7 @@ static void prim_appendContext(EvalState & state, const Pos & pos, Value * * arg
.errPos = *i.pos .errPos = *i.pos
}); });
} }
context.insert("=" + string(i.name)); context.insert("=" + std::string(i.name));
} }
} }

View file

@ -62,7 +62,7 @@ static void prim_fetchMercurial(EvalState & state, const Pos & pos, Value * * ar
fetchers::Attrs attrs; fetchers::Attrs attrs;
attrs.insert_or_assign("type", "hg"); attrs.insert_or_assign("type", "hg");
attrs.insert_or_assign("url", url.find("://") != std::string::npos ? url : "file://" + url); 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 (ref) attrs.insert_or_assign("ref", *ref);
if (rev) attrs.insert_or_assign("rev", rev->gitRev()); if (rev) attrs.insert_or_assign("rev", rev->gitRev());
auto input = fetchers::Input::fromAttrs(std::move(attrs)); auto input = fetchers::Input::fromAttrs(std::move(attrs));

View file

@ -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 RegisterPrimOp primop_fetchTree("fetchTree", 1, prim_fetchTree);
static void fetch(EvalState & state, const Pos & pos, Value * * args, Value & v, 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<std::string> url; std::optional<std::string> url;
std::optional<Hash> expectedHash; std::optional<Hash> expectedHash;
@ -198,7 +198,7 @@ static void fetch(EvalState & state, const Pos & pos, Value * * args, Value & v,
state.forceAttrs(*args[0], pos); state.forceAttrs(*args[0], pos);
for (auto & attr : *args[0]->attrs) { for (auto & attr : *args[0]->attrs) {
string n(attr.name); std::string n(attr.name);
if (n == "url") if (n == "url")
url = state.forceStringNoCtx(*attr.value, *attr.pos); url = state.forceStringNoCtx(*attr.value, *attr.pos);
else if (n == "sha256") else if (n == "sha256")

View file

@ -9,7 +9,7 @@ static void prim_fromTOML(EvalState & state, const Pos & pos, Value * * args, Va
{ {
auto toml = state.forceStringNoCtx(*args[0], pos); auto toml = state.forceStringNoCtx(*args[0], pos);
std::istringstream tomlStream(string{toml}); std::istringstream tomlStream(std::string{toml});
std::function<void(Value &, toml::value)> visit; std::function<void(Value &, toml::value)> visit;

View file

@ -9,7 +9,7 @@
namespace nix { namespace nix {
static XMLAttrs singletonAttrs(const string & name, const string & value) static XMLAttrs singletonAttrs(const std::string & name, const std::string & value)
{ {
XMLAttrs attrs; XMLAttrs attrs;
attrs[name] = value; attrs[name] = value;

View file

@ -26,7 +26,7 @@ static RunOptions hgOptions(const Strings & args)
} }
// runProgram wrapper that uses hgOptions instead of stock RunOptions. // runProgram wrapper that uses hgOptions instead of stock RunOptions.
static string runHg(const Strings & args, const std::optional<std::string> & input = {}) static std::string runHg(const Strings & args, const std::optional<std::string> & input = {})
{ {
RunOptions opts = hgOptions(args); RunOptions opts = hgOptions(args);
opts.input = input; opts.input = input;
@ -254,7 +254,7 @@ struct MercurialInputScheme : InputScheme
runHg({ "pull", "-R", cacheDir, "--", actualUrl }); runHg({ "pull", "-R", cacheDir, "--", actualUrl });
} }
catch (ExecError & e) { 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 */ /* hg throws "abandoned transaction" error only if this file exists */
if (pathExists(transJournal)) { if (pathExists(transJournal)) {
runHg({ "recover", "-R", cacheDir }); runHg({ "recover", "-R", cacheDir });

View file

@ -4,7 +4,7 @@
namespace nix { namespace nix {
MixCommonArgs::MixCommonArgs(const string & programName) MixCommonArgs::MixCommonArgs(const std::string & programName)
: programName(programName) : programName(programName)
{ {
addFlag({ addFlag({

View file

@ -11,8 +11,8 @@ class MixCommonArgs : public virtual Args
{ {
void initialFlagsProcessed() override; void initialFlagsProcessed() override;
public: public:
string programName; std::string programName;
MixCommonArgs(const string & programName); MixCommonArgs(const std::string & programName);
protected: protected:
virtual void pluginsInited() {} virtual void pluginsInited() {}
}; };

View file

@ -94,7 +94,7 @@ void printMissing(ref<Store> store, const StorePathSet & willBuild,
} }
string getArg(const string & opt, std::string getArg(const std::string & opt,
Strings::iterator & i, const Strings::iterator & end) Strings::iterator & i, const Strings::iterator & end)
{ {
++i; ++i;
@ -227,6 +227,8 @@ LegacyArgs::LegacyArgs(const std::string & programName,
std::function<bool(Strings::iterator & arg, const Strings::iterator & end)> parseArg) std::function<bool(Strings::iterator & arg, const Strings::iterator & end)> parseArg)
: MixCommonArgs(programName), parseArg(parseArg) : MixCommonArgs(programName), parseArg(parseArg)
{ {
printError("FOO %s", programName);
addFlag({ addFlag({
.longName = "no-build-output", .longName = "no-build-output",
.shortName = 'Q', .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<bool(Strings::iterator & arg, const Strings::iterator & end)> parseArg) std::function<bool(Strings::iterator & arg, const Strings::iterator & end)> parseArg)
{ {
LegacyArgs(programName, parseArg).parseCmdline(args); 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; std::cout << format("%1% (Nix) %2%") % programName % nixVersion << std::endl;
if (verbosity > lvlInfo) { if (verbosity > lvlInfo) {
@ -352,7 +354,7 @@ void printVersion(const string & programName)
} }
void showManPage(const string & name) void showManPage(const std::string & name)
{ {
restoreProcessContext(); restoreProcessContext();
setenv("MANPATH", settings.nixManDir.c_str(), 1); setenv("MANPATH", settings.nixManDir.c_str(), 1);
@ -361,13 +363,13 @@ void showManPage(const string & name)
} }
int handleExceptions(const string & programName, std::function<void()> fun) int handleExceptions(const std::string & programName, std::function<void()> fun)
{ {
ReceiveInterrupts receiveInterrupts; // FIXME: need better place for this ReceiveInterrupts receiveInterrupts; // FIXME: need better place for this
ErrorInfo::programName = baseNameOf(programName); ErrorInfo::programName = baseNameOf(programName);
string error = ANSI_RED "error:" ANSI_NORMAL " "; std::string error = ANSI_RED "error:" ANSI_NORMAL " ";
try { try {
try { try {
fun(); fun();
@ -407,7 +409,7 @@ RunPager::RunPager()
if (!isatty(STDOUT_FILENO)) return; if (!isatty(STDOUT_FILENO)) return;
char * pager = getenv("NIX_PAGER"); char * pager = getenv("NIX_PAGER");
if (!pager) pager = getenv("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; Pipe toPager;
toPager.create(); toPager.create();

View file

@ -22,7 +22,7 @@ public:
virtual ~Exit(); virtual ~Exit();
}; };
int handleExceptions(const string & programName, std::function<void()> fun); int handleExceptions(const std::string & programName, std::function<void()> fun);
/* Don't forget to call initPlugins() after settings are initialized! */ /* Don't forget to call initPlugins() after settings are initialized! */
void initNix(); void initNix();
@ -30,10 +30,10 @@ void initNix();
void parseCmdLine(int argc, char * * argv, void parseCmdLine(int argc, char * * argv,
std::function<bool(Strings::iterator & arg, const Strings::iterator & end)> parseArg); std::function<bool(Strings::iterator & arg, const Strings::iterator & end)> parseArg);
void parseCmdLine(const string & programName, const Strings & args, void parseCmdLine(const std::string & programName, const Strings & args,
std::function<bool(Strings::iterator & arg, const Strings::iterator & end)> parseArg); std::function<bool(Strings::iterator & arg, const Strings::iterator & end)> parseArg);
void printVersion(const string & programName); void printVersion(const std::string & programName);
/* Ugh. No better place to put this. */ /* Ugh. No better place to put this. */
void printGCWarning(); void printGCWarning();
@ -50,10 +50,10 @@ void printMissing(ref<Store> store, const StorePathSet & willBuild,
const StorePathSet & willSubstitute, const StorePathSet & unknown, const StorePathSet & willSubstitute, const StorePathSet & unknown,
uint64_t downloadSize, uint64_t narSize, Verbosity lvl = lvlInfo); 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); Strings::iterator & i, const Strings::iterator & end);
template<class N> N getIntArg(const string & opt, template<class N> N getIntArg(const std::string & opt,
Strings::iterator & i, const Strings::iterator & end, bool allowUnit) Strings::iterator & i, const Strings::iterator & end, bool allowUnit)
{ {
++i; ++i;
@ -76,7 +76,7 @@ struct LegacyArgs : public MixCommonArgs
/* Show the manual page for the specified program. */ /* 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 /* The constructor of this class starts a pager if stdout is a
terminal and $PAGER is set. Stdout is redirected to the pager. */ terminal and $PAGER is set. Stdout is redirected to the pager. */
@ -96,7 +96,7 @@ extern volatile ::sig_atomic_t blockInt;
/* GC helpers. */ /* GC helpers. */
string showBytes(uint64_t bytes); std::string showBytes(uint64_t bytes);
struct GCResults; struct GCResults;

View file

@ -385,8 +385,14 @@ void BinaryCacheStore::queryPathInfoUncached(const StorePath & storePath,
}}); }});
} }
StorePath BinaryCacheStore::addToStore(const string & name, const Path & srcPath, StorePath BinaryCacheStore::addToStore(
FileIngestionMethod method, HashType hashAlgo, PathFilter & filter, RepairFlag repair, const StorePathSet & references) std::string_view name,
const Path & srcPath,
FileIngestionMethod method,
HashType hashAlgo,
PathFilter & filter,
RepairFlag repair,
const StorePathSet & references)
{ {
/* FIXME: Make BinaryCacheStore::addToStoreCommon support /* FIXME: Make BinaryCacheStore::addToStoreCommon support
non-recursive+sha256 so we can just use the default non-recursive+sha256 so we can just use the default
@ -418,8 +424,11 @@ StorePath BinaryCacheStore::addToStore(const string & name, const Path & srcPath
})->path; })->path;
} }
StorePath BinaryCacheStore::addTextToStore(const string & name, const string & s, StorePath BinaryCacheStore::addTextToStore(
const StorePathSet & references, RepairFlag repair) std::string_view name,
std::string_view s,
const StorePathSet & references,
RepairFlag repair)
{ {
auto textHash = hashString(htSHA256, s); auto textHash = hashString(htSHA256, s);
auto path = makeTextPath(name, textHash, references); auto path = makeTextPath(name, textHash, references);

View file

@ -101,12 +101,20 @@ public:
StorePath addToStoreFromDump(Source & dump, std::string_view name, StorePath addToStoreFromDump(Source & dump, std::string_view name,
FileIngestionMethod method, HashType hashAlgo, RepairFlag repair, const StorePathSet & references) override; FileIngestionMethod method, HashType hashAlgo, RepairFlag repair, const StorePathSet & references) override;
StorePath addToStore(const string & name, const Path & srcPath, StorePath addToStore(
FileIngestionMethod method, HashType hashAlgo, std::string_view name,
PathFilter & filter, RepairFlag repair, const StorePathSet & references) override; const Path & srcPath,
FileIngestionMethod method,
HashType hashAlgo,
PathFilter & filter,
RepairFlag repair,
const StorePathSet & references) override;
StorePath addTextToStore(const string & name, const string & s, StorePath addTextToStore(
const StorePathSet & references, RepairFlag repair) override; std::string_view name,
std::string_view s,
const StorePathSet & references,
RepairFlag repair) override;
void registerDrvOutput(const Realisation & info) override; void registerDrvOutput(const Realisation & info) override;

View file

@ -116,7 +116,7 @@ DerivationGoal::~DerivationGoal()
} }
string DerivationGoal::key() std::string DerivationGoal::key()
{ {
/* Ensure that derivations get built in order of their name, /* Ensure that derivations get built in order of their name,
i.e. a derivation named "aardvark" always comes before 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 /* Read the first line of input, which should be a word indicating
whether the hook wishes to perform the build. */ whether the hook wishes to perform the build. */
string reply; std::string reply;
while (true) { while (true) {
auto s = [&]() { auto s = [&]() {
try { try {
@ -1025,8 +1025,8 @@ HookReply DerivationGoal::tryBuildHook()
}(); }();
if (handleJSONLogMessage(s, worker.act, worker.hook->activities, true)) if (handleJSONLogMessage(s, worker.act, worker.hook->activities, true))
; ;
else if (string(s, 0, 2) == "# ") { else if (s.substr(0, 2) == "# ") {
reply = string(s, 2); reply = s.substr(2);
break; break;
} }
else { else {
@ -1140,10 +1140,10 @@ Path DerivationGoal::openLogFile()
logDir = localStore->logDir; logDir = localStore->logDir;
else else
logDir = settings.nixLogDir; 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); 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" : ""); settings.compressLog ? ".bz2" : "");
fdLogFile = open(logFileName.c_str(), O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC, 0666); 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)) if (isReadDesc(fd))
{ {

View file

@ -145,7 +145,7 @@ struct DerivationGoal : public Goal
void timedOut(Error && ex) override; void timedOut(Error && ex) override;
string key() override; std::string key() override;
void work() override; void work() override;
@ -200,7 +200,7 @@ struct DerivationGoal : public Goal
virtual bool isReadDesc(int fd); virtual bool isReadDesc(int fd);
/* Callback used by the worker to write to the log. */ /* 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 handleEOF(int fd) override;
void flushLine(); void flushLine();

View file

@ -137,7 +137,7 @@ void DrvOutputSubstitutionGoal::finished()
amDone(ecSuccess); amDone(ecSuccess);
} }
string DrvOutputSubstitutionGoal::key() std::string DrvOutputSubstitutionGoal::key()
{ {
/* "a$" ensures substitution goals happen before derivation /* "a$" ensures substitution goals happen before derivation
goals. */ goals. */

View file

@ -51,7 +51,7 @@ public:
void timedOut(Error && ex) override { abort(); }; void timedOut(Error && ex) override { abort(); };
string key() override; std::string key() override;
void work() override; void work() override;
void handleEOF(int fd) override; void handleEOF(int fd) override;

View file

@ -5,8 +5,8 @@ namespace nix {
bool CompareGoalPtrs::operator() (const GoalPtr & a, const GoalPtr & b) const { bool CompareGoalPtrs::operator() (const GoalPtr & a, const GoalPtr & b) const {
string s1 = a->key(); std::string s1 = a->key();
string s2 = b->key(); std::string s2 = b->key();
return s1 < s2; return s1 < s2;
} }

View file

@ -50,7 +50,7 @@ struct Goal : public std::enable_shared_from_this<Goal>
unsigned int nrIncompleteClosure; unsigned int nrIncompleteClosure;
/* Name of this goal for debugging purposes. */ /* Name of this goal for debugging purposes. */
string name; std::string name;
/* Whether the goal is finished. */ /* Whether the goal is finished. */
ExitCode exitCode; ExitCode exitCode;
@ -75,7 +75,7 @@ struct Goal : public std::enable_shared_from_this<Goal>
virtual void waiteeDone(GoalPtr waitee, ExitCode result); 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(); abort();
} }
@ -87,7 +87,7 @@ struct Goal : public std::enable_shared_from_this<Goal>
void trace(const FormatOrString & fs); void trace(const FormatOrString & fs);
string getName() std::string getName()
{ {
return name; return name;
} }
@ -97,7 +97,7 @@ struct Goal : public std::enable_shared_from_this<Goal>
by the worker (important!), etc. */ by the worker (important!), etc. */
virtual void timedOut(Error && ex) = 0; virtual void timedOut(Error && ex) = 0;
virtual string key() = 0; virtual std::string key() = 0;
void amDone(ExitCode result, std::optional<Error> ex = {}); void amDone(ExitCode result, std::optional<Error> ex = {});

View file

@ -481,12 +481,12 @@ void LocalDerivationGoal::startBuilder()
temporary build directory. The text files have the format used temporary build directory. The text files have the format used
by `nix-store --register-validity'. However, the deriver by `nix-store --register-validity'. However, the deriver
fields are left empty. */ fields are left empty. */
string s = get(drv->env, "exportReferencesGraph").value_or(""); auto s = get(drv->env, "exportReferencesGraph").value_or("");
Strings ss = tokenizeString<Strings>(s); Strings ss = tokenizeString<Strings>(s);
if (ss.size() % 2 != 0) if (ss.size() % 2 != 0)
throw BuildError("odd number of tokens in 'exportReferencesGraph': '%1%'", s); throw BuildError("odd number of tokens in 'exportReferencesGraph': '%1%'", s);
for (Strings::iterator i = ss.begin(); i != ss.end(); ) { 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_.-]*"); static std::regex regex("[A-Za-z_][A-Za-z0-9_.-]*");
if (!std::regex_match(fileName, regex)) if (!std::regex_match(fileName, regex))
throw Error("invalid file name '%s' in 'exportReferencesGraph'", fileName); throw Error("invalid file name '%s' in 'exportReferencesGraph'", fileName);
@ -517,10 +517,10 @@ void LocalDerivationGoal::startBuilder()
i.pop_back(); i.pop_back();
} }
size_t p = i.find('='); size_t p = i.find('=');
if (p == string::npos) if (p == std::string::npos)
dirsInChroot[i] = {i, optional}; dirsInChroot[i] = {i, optional};
else else
dirsInChroot[string(i, 0, p)] = {string(i, p + 1), optional}; dirsInChroot[i.substr(0, p)] = {i.substr(p + 1), optional};
} }
dirsInChroot[tmpDirInSandbox] = tmpDir; dirsInChroot[tmpDirInSandbox] = tmpDir;
@ -671,9 +671,10 @@ void LocalDerivationGoal::startBuilder()
auto state = stBegin; auto state = stBegin;
auto lines = runProgram(settings.preBuildHook, false, args); auto lines = runProgram(settings.preBuildHook, false, args);
auto lastPos = std::string::size_type{0}; auto lastPos = std::string::size_type{0};
for (auto nlPos = lines.find('\n'); nlPos != string::npos; for (auto nlPos = lines.find('\n'); nlPos != std::string::npos;
nlPos = lines.find('\n', lastPos)) { nlPos = lines.find('\n', lastPos))
auto line = std::string{lines, lastPos, nlPos - lastPos}; {
auto line = lines.substr(lastPos, nlPos - lastPos);
lastPos = nlPos + 1; lastPos = nlPos + 1;
if (state == stBegin) { if (state == stBegin) {
if (line == "extra-sandbox-paths" || line == "extra-chroot-dirs") { if (line == "extra-sandbox-paths" || line == "extra-chroot-dirs") {
@ -686,10 +687,10 @@ void LocalDerivationGoal::startBuilder()
state = stBegin; state = stBegin;
} else { } else {
auto p = line.find('='); auto p = line.find('=');
if (p == string::npos) if (p == std::string::npos)
dirsInChroot[line] = line; dirsInChroot[line] = line;
else 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. */ /* Check if setting up the build environment failed. */
std::vector<std::string> msgs; std::vector<std::string> msgs;
while (true) { while (true) {
string msg = [&]() { std::string msg = [&]() {
try { try {
return readLine(builderOut.readSide.get()); return readLine(builderOut.readSide.get());
} catch (Error & e) { } catch (Error & e) {
@ -953,8 +954,8 @@ void LocalDerivationGoal::startBuilder()
throw; throw;
} }
}(); }();
if (string(msg, 0, 1) == "\2") break; if (msg.substr(0, 1) == "\2") break;
if (string(msg, 0, 1) == "\1") { if (msg.substr(0, 1) == "\1") {
FdSource source(builderOut.readSide.get()); FdSource source(builderOut.readSide.get());
auto ex = readError(source); auto ex = readError(source);
ex.addTrace({}, "while setting up the build environment"); ex.addTrace({}, "while setting up the build environment");
@ -990,7 +991,7 @@ void LocalDerivationGoal::initTmpDir() {
env[i.first] = i.second; env[i.first] = i.second;
} else { } else {
auto hash = hashString(htSHA256, i.first); 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; Path p = tmpDir + "/" + fn;
writeFile(p, rewriteStrings(i.second, inputRewrites)); writeFile(p, rewriteStrings(i.second, inputRewrites));
chownToBuilder(p); chownToBuilder(p);
@ -1081,7 +1082,7 @@ void LocalDerivationGoal::writeStructuredAttrs()
for (auto & [i, v] : json["outputs"].get<nlohmann::json::object_t>()) { for (auto & [i, v] : json["outputs"].get<nlohmann::json::object_t>()) {
/* The placeholder must have a rewrite, so we use it to cover both the /* 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. */ 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; json["outputs"] = rewritten;
@ -1187,10 +1188,14 @@ struct RestrictedStore : public virtual RestrictedStoreConfig, public virtual Lo
std::optional<StorePath> queryPathFromHashPart(const std::string & hashPart) override std::optional<StorePath> queryPathFromHashPart(const std::string & hashPart) override
{ throw Error("queryPathFromHashPart"); } { throw Error("queryPathFromHashPart"); }
StorePath addToStore(const string & name, const Path & srcPath, StorePath addToStore(
FileIngestionMethod method = FileIngestionMethod::Recursive, HashType hashAlgo = htSHA256, std::string_view name,
PathFilter & filter = defaultPathFilter, RepairFlag repair = NoRepair, const Path & srcPath,
const StorePathSet & references = StorePathSet()) override FileIngestionMethod method,
HashType hashAlgo,
PathFilter & filter,
RepairFlag repair,
const StorePathSet & references) override
{ throw Error("addToStore"); } { throw Error("addToStore"); }
void addToStore(const ValidPathInfo & info, Source & narSource, void addToStore(const ValidPathInfo & info, Source & narSource,
@ -1200,17 +1205,24 @@ struct RestrictedStore : public virtual RestrictedStoreConfig, public virtual Lo
goal.addDependency(info.path); goal.addDependency(info.path);
} }
StorePath addTextToStore(const string & name, const string & s, StorePath addTextToStore(
const StorePathSet & references, RepairFlag repair = NoRepair) override std::string_view name,
std::string_view s,
const StorePathSet & references,
RepairFlag repair = NoRepair) override
{ {
auto path = next->addTextToStore(name, s, references, repair); auto path = next->addTextToStore(name, s, references, repair);
goal.addDependency(path); goal.addDependency(path);
return path; return path;
} }
StorePath addToStoreFromDump(Source & dump, std::string_view name, StorePath addToStoreFromDump(
FileIngestionMethod method = FileIngestionMethod::Recursive, HashType hashAlgo = htSHA256, RepairFlag repair = NoRepair, Source & dump,
const StorePathSet & references = StorePathSet()) override std::string_view name,
FileIngestionMethod method,
HashType hashAlgo,
RepairFlag repair,
const StorePathSet & references) override
{ {
auto path = next->addToStoreFromDump(dump, name, method, hashAlgo, repair, references); auto path = next->addToStoreFromDump(dump, name, method, hashAlgo, repair, references);
goal.addDependency(path); goal.addDependency(path);
@ -1992,7 +2004,7 @@ void LocalDerivationGoal::runChild()
args.push_back(rewriteStrings(i, inputRewrites)); args.push_back(rewriteStrings(i, inputRewrites));
/* Indicate that we managed to set up the build environment. */ /* 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. */ /* Execute the program. This should not return. */
if (drv->isBuiltin()) { if (drv->isBuiltin()) {
@ -2010,7 +2022,7 @@ void LocalDerivationGoal::runChild()
else if (drv->builder == "builtin:unpack-channel") else if (drv->builder == "builtin:unpack-channel")
builtinUnpackChannel(drv2); builtinUnpackChannel(drv2);
else else
throw Error("unsupported builtin builder '%1%'", string(drv->builder, 8)); throw Error("unsupported builtin builder '%1%'", drv->builder.substr(8));
_exit(0); _exit(0);
} catch (std::exception & e) { } catch (std::exception & e) {
writeFull(STDERR_FILENO, e.what() + std::string("\n")); writeFull(STDERR_FILENO, e.what() + std::string("\n"));
@ -2694,7 +2706,7 @@ void LocalDerivationGoal::checkOutputs(const std::map<Path, ValidPathInfo> & out
} }
if (!badPaths.empty()) { if (!badPaths.empty()) {
string badPathsStr; std::string badPathsStr;
for (auto & i : badPaths) { for (auto & i : badPaths) {
badPathsStr += "\n "; badPathsStr += "\n ";
badPathsStr += worker.store.printStorePath(i); badPathsStr += worker.store.printStorePath(i);

View file

@ -58,7 +58,7 @@ struct LocalDerivationGoal : public DerivationGoal
typedef map<Path, ChrootPath> DirsInChroot; // maps target path to source path typedef map<Path, ChrootPath> DirsInChroot; // maps target path to source path
DirsInChroot dirsInChroot; DirsInChroot dirsInChroot;
typedef map<string, string> Environment; typedef map<std::string, std::string> Environment;
Environment env; Environment env;
#if __APPLE__ #if __APPLE__

View file

@ -272,7 +272,7 @@ void PathSubstitutionGoal::finished()
} }
void PathSubstitutionGoal::handleChildOutput(int fd, const string & data) void PathSubstitutionGoal::handleChildOutput(int fd, std::string_view data)
{ {
} }

View file

@ -59,7 +59,7 @@ public:
void timedOut(Error && ex) override { abort(); }; void timedOut(Error && ex) override { abort(); };
string key() override std::string key() override
{ {
/* "a$" ensures substitution goals happen before derivation /* "a$" ensures substitution goals happen before derivation
goals. */ goals. */
@ -77,7 +77,7 @@ public:
void finished(); void finished();
/* Callback used by the worker to write to the log. */ /* 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 handleEOF(int fd) override;
void cleanup() override; void cleanup() override;

View file

@ -394,7 +394,7 @@ void Worker::waitForInput()
} else { } else {
printMsg(lvlVomit, "%1%: read %2% bytes", printMsg(lvlVomit, "%1%: read %2% bytes",
goal->getName(), rd); goal->getName(), rd);
string data((char *) buffer.data(), rd); std::string data((char *) buffer.data(), rd);
j->lastOutput = after; j->lastOutput = after;
goal->handleChildOutput(k, data); goal->handleChildOutput(k, data);
} }

View file

@ -123,7 +123,7 @@ void buildProfile(const Path & out, Packages && pkgs)
createLinks(state, pkgDir, out, priority); createLinks(state, pkgDir, out, priority);
try { try {
for (const auto & p : tokenizeString<std::vector<string>>( for (const auto & p : tokenizeString<std::vector<std::string>>(
readFile(pkgDir + "/nix-support/propagated-user-env-packages"), " \n")) readFile(pkgDir + "/nix-support/propagated-user-env-packages"), " \n"))
if (!done.count(p)) if (!done.count(p))
postponed.insert(p); postponed.insert(p);
@ -161,7 +161,7 @@ void buildProfile(const Path & out, Packages && pkgs)
void builtinBuildenv(const BasicDerivation & drv) void builtinBuildenv(const BasicDerivation & drv)
{ {
auto getAttr = [&](const string & name) { auto getAttr = [&](const std::string & name) {
auto i = drv.env.find(name); auto i = drv.env.find(name);
if (i == drv.env.end()) throw Error("attribute '%s' missing", name); if (i == drv.env.end()) throw Error("attribute '%s' missing", name);
return i->second; return i->second;

View file

@ -16,7 +16,7 @@ void builtinFetchurl(const BasicDerivation & drv, const std::string & netrcData)
writeFile(settings.netrcFile, netrcData, 0600); writeFile(settings.netrcFile, netrcData, 0600);
} }
auto getAttr = [&](const string & name) { auto getAttr = [&](const std::string & name) {
auto i = drv.env.find(name); auto i = drv.env.find(name);
if (i == drv.env.end()) throw Error("attribute '%s' missing", name); if (i == drv.env.end()) throw Error("attribute '%s' missing", name);
return i->second; return i->second;

View file

@ -5,7 +5,7 @@ namespace nix {
void builtinUnpackChannel(const BasicDerivation & drv) void builtinUnpackChannel(const BasicDerivation & drv)
{ {
auto getAttr = [&](const string & name) { auto getAttr = [&](const std::string & name) {
auto i = drv.env.find(name); auto i = drv.env.find(name);
if (i == drv.env.end()) throw Error("attribute '%s' missing", name); if (i == drv.env.end()) throw Error("attribute '%s' missing", name);
return i->second; return i->second;

View file

@ -479,8 +479,8 @@ static void performOp(TunnelLogger * logger, ref<Store> store,
} }
case wopAddTextToStore: { case wopAddTextToStore: {
string suffix = readString(from); std::string suffix = readString(from);
string s = readString(from); std::string s = readString(from);
auto refs = worker_proto::read(*store, from, Phantom<StorePathSet> {}); auto refs = worker_proto::read(*store, from, Phantom<StorePathSet> {});
logger->startWork(); logger->startWork();
auto path = store->addTextToStore(suffix, s, refs, NoRepair); auto path = store->addTextToStore(suffix, s, refs, NoRepair);
@ -698,8 +698,8 @@ static void performOp(TunnelLogger * logger, ref<Store> store,
if (GET_PROTOCOL_MINOR(clientVersion) >= 12) { if (GET_PROTOCOL_MINOR(clientVersion) >= 12) {
unsigned int n = readInt(from); unsigned int n = readInt(from);
for (unsigned int i = 0; i < n; i++) { for (unsigned int i = 0; i < n; i++) {
string name = readString(from); auto name = readString(from);
string value = readString(from); auto value = readString(from);
clientSettings.overrides.emplace(name, value); clientSettings.overrides.emplace(name, value);
} }
} }

View file

@ -82,7 +82,7 @@ bool derivationIsImpure(DerivationType dt) {
bool BasicDerivation::isBuiltin() const 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'. */ /* 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()]; char s2[s.size()];
str.read(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); throw FormatError("expected string '%1%'", s);
} }
/* Read a C-style string from stream `str'. */ /* 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, "\""); expect(str, "\"");
int c; int c;
while ((c = str.get()) != '"') while ((c = str.get()) != '"')
@ -172,7 +172,7 @@ static DerivationOutput parseDerivationOutput(const Store & store,
{ {
if (hashAlgo != "") { if (hashAlgo != "") {
auto method = FileIngestionMethod::Flat; auto method = FileIngestionMethod::Flat;
if (string(hashAlgo, 0, 2) == "r:") { if (hashAlgo.substr(0, 2) == "r:") {
method = FileIngestionMethod::Recursive; method = FileIngestionMethod::Recursive;
hashAlgo = hashAlgo.substr(2); hashAlgo = hashAlgo.substr(2);
} }
@ -260,8 +260,8 @@ Derivation parseDerivation(const Store & store, std::string && s, std::string_vi
/* Parse the environment variables. */ /* Parse the environment variables. */
expect(str, ",["); expect(str, ",[");
while (!endOfList(str)) { while (!endOfList(str)) {
expect(str, "("); string name = parseString(str); expect(str, "("); auto name = parseString(str);
expect(str, ","); string value = parseString(str); expect(str, ","); auto value = parseString(str);
expect(str, ")"); expect(str, ")");
drv.env[name] = value; 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<char, 64 * 1024> buffer; boost::container::small_vector<char, 64 * 1024> buffer;
buffer.reserve(s.size() * 2 + 2); 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 += '"';
res.append(s); res.append(s);
@ -298,7 +298,7 @@ static void printUnquotedString(string & res, std::string_view s)
template<class ForwardIterator> template<class ForwardIterator>
static void printStrings(string & res, ForwardIterator i, ForwardIterator j) static void printStrings(std::string & res, ForwardIterator i, ForwardIterator j)
{ {
res += '['; res += '[';
bool first = true; bool first = true;
@ -311,7 +311,7 @@ static void printStrings(string & res, ForwardIterator i, ForwardIterator j)
template<class ForwardIterator> template<class ForwardIterator>
static void printUnquotedStrings(string & res, ForwardIterator i, ForwardIterator j) static void printUnquotedStrings(std::string & res, ForwardIterator i, ForwardIterator j)
{ {
res += '['; res += '[';
bool first = true; 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<std::string, StringSet> * actualInputs) const std::map<std::string, StringSet> * actualInputs) const
{ {
string s; std::string s;
s.reserve(65536); s.reserve(65536);
s += "Derive(["; s += "Derive([";
@ -401,7 +401,7 @@ string Derivation::unparse(const Store & store, bool maskOutputs,
// FIXME: remove // FIXME: remove
bool isDerivation(const string & fileName) bool isDerivation(const std::string & fileName)
{ {
return hasSuffix(fileName, drvExtension); return hasSuffix(fileName, drvExtension);
} }
@ -593,7 +593,7 @@ std::map<std::string, Hash> staticOutputHashes(Store & store, const Derivation &
} }
bool wantOutput(const string & output, const std::set<string> & wanted) bool wantOutput(const std::string & output, const std::set<std::string> & wanted)
{ {
return wanted.empty() || wanted.find(output) != wanted.end(); return wanted.empty() || wanted.find(output) != wanted.end();
} }

View file

@ -59,21 +59,19 @@ struct DerivationOutput
std::optional<StorePath> path(const Store & store, std::string_view drvName, std::string_view outputName) const; std::optional<StorePath> path(const Store & store, std::string_view drvName, std::string_view outputName) const;
}; };
typedef std::map<string, DerivationOutput> DerivationOutputs; typedef std::map<std::string, DerivationOutput> DerivationOutputs;
/* These are analogues to the previous DerivationOutputs data type, but they /* These are analogues to the previous DerivationOutputs data type, but they
also contains, for each output, the (optional) store path in which it would also contains, for each output, the (optional) store path in which it would
be written. To calculate values of these types, see the corresponding be written. To calculate values of these types, see the corresponding
functions in BasicDerivation */ functions in BasicDerivation */
typedef std::map<string, std::pair<DerivationOutput, std::optional<StorePath>>> typedef std::map<std::string, std::pair<DerivationOutput, std::optional<StorePath>>>
DerivationOutputsAndOptPaths; DerivationOutputsAndOptPaths;
/* For inputs that are sub-derivations, we specify exactly which /* For inputs that are sub-derivations, we specify exactly which
output IDs we are interested in. */ output IDs we are interested in. */
typedef std::map<StorePath, StringSet> DerivationInputs; typedef std::map<StorePath, StringSet> DerivationInputs;
typedef std::map<string, string> StringPairs;
enum struct DerivationType : uint8_t { enum struct DerivationType : uint8_t {
InputAddressed, InputAddressed,
DeferredInputAddressed, DeferredInputAddressed,
@ -103,7 +101,7 @@ struct BasicDerivation
{ {
DerivationOutputs outputs; /* keyed on symbolic IDs */ DerivationOutputs outputs; /* keyed on symbolic IDs */
StorePathSet inputSrcs; /* inputs that are sources */ StorePathSet inputSrcs; /* inputs that are sources */
string platform; std::string platform;
Path builder; Path builder;
Strings args; Strings args;
StringPairs env; StringPairs env;
@ -164,7 +162,7 @@ StorePath writeDerivation(Store & store,
Derivation parseDerivation(const Store & store, std::string && s, std::string_view name); Derivation parseDerivation(const Store & store, std::string && s, std::string_view name);
// FIXME: remove // 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 /* Calculate the name that will be used for the store path for this
output. output.
@ -222,7 +220,7 @@ typedef std::map<StorePath, DrvHashModulo> DrvHashes;
// FIXME: global, though at least thread-safe. // FIXME: global, though at least thread-safe.
extern Sync<DrvHashes> drvHashes; extern Sync<DrvHashes> drvHashes;
bool wantOutput(const string & output, const std::set<string> & wanted); bool wantOutput(const std::string & output, const std::set<std::string> & wanted);
struct Source; struct Source;
struct Sink; struct Sink;

View file

@ -75,9 +75,9 @@ DerivedPath::Built DerivedPath::Built::parse(const Store & store, std::string_vi
assert(n != s.npos); assert(n != s.npos);
auto drvPath = store.parseStorePath(s.substr(0, n)); auto drvPath = store.parseStorePath(s.substr(0, n));
auto outputsS = s.substr(n + 1); auto outputsS = s.substr(n + 1);
std::set<string> outputs; std::set<std::string> outputs;
if (outputsS != "*") if (outputsS != "*")
outputs = tokenizeString<std::set<string>>(outputsS, ","); outputs = tokenizeString<std::set<std::string>>(outputsS, ",");
return {drvPath, outputs}; return {drvPath, outputs};
} }

View file

@ -21,7 +21,7 @@ struct DummyStore : public virtual DummyStoreConfig, public virtual Store
, Store(params) , Store(params)
{ } { }
string getUri() override std::string getUri() override
{ {
return *uriSchemes().begin(); return *uriSchemes().begin();
} }
@ -43,8 +43,11 @@ struct DummyStore : public virtual DummyStoreConfig, public virtual Store
RepairFlag repair, CheckSigsFlag checkSigs) override RepairFlag repair, CheckSigsFlag checkSigs) override
{ unsupported("addToStore"); } { unsupported("addToStore"); }
StorePath addTextToStore(const string & name, const string & s, StorePath addTextToStore(
const StorePathSet & references, RepairFlag repair) override std::string_view name,
std::string_view s,
const StorePathSet & references,
RepairFlag repair) override
{ unsupported("addTextToStore"); } { unsupported("addTextToStore"); }
void narFromPath(const StorePath & path, Sink & sink) override void narFromPath(const StorePath & path, Sink & sink) override

View file

@ -33,12 +33,12 @@ FileTransferSettings fileTransferSettings;
static GlobalConfig::Register rFileTransferSettings(&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) 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 else
return uri; return std::string(uri);
} }
struct curlFileTransfer : public FileTransfer struct curlFileTransfer : public FileTransfer
@ -197,15 +197,15 @@ struct curlFileTransfer : public FileTransfer
result.etag = ""; result.etag = "";
result.data.clear(); result.data.clear();
result.bodySize = 0; result.bodySize = 0;
statusMsg = trim(match[1]); statusMsg = trim((std::string &) match[1]);
acceptRanges = false; acceptRanges = false;
encoding = ""; encoding = "";
} else { } else {
auto i = line.find(':'); auto i = line.find(':');
if (i != string::npos) { if (i != std::string::npos) {
string name = toLower(trim(string(line, 0, i))); std::string name = toLower(trim(line.substr(0, i)));
if (name == "etag") { 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 /* Hack to work around a GitHub bug: it sends
ETags, but ignores If-None-Match. So if we get ETags, but ignores If-None-Match. So if we get
the expected ETag on a 200 response, then shut the expected ETag on a 200 response, then shut
@ -218,8 +218,8 @@ struct curlFileTransfer : public FileTransfer
return 0; return 0;
} }
} else if (name == "content-encoding") } else if (name == "content-encoding")
encoding = trim(string(line, i + 1)); encoding = trim(line.substr(i + 1));
else if (name == "accept-ranges" && toLower(trim(std::string(line, i + 1))) == "bytes") else if (name == "accept-ranges" && toLower(trim(line.substr(i + 1))) == "bytes")
acceptRanges = true; acceptRanges = true;
} }
} }
@ -866,18 +866,18 @@ FileTransferError::FileTransferError(FileTransfer::Error error, std::optional<st
// FIXME: Due to https://github.com/NixOS/nix/issues/3841 we don't know how // FIXME: Due to https://github.com/NixOS/nix/issues/3841 we don't know how
// to print different messages for different verbosity levels. For now // to print different messages for different verbosity levels. For now
// we add some heuristics for detecting when we want to show the response. // we add some heuristics for detecting when we want to show the response.
if (response && (response->size() < 1024 || response->find("<html>") != string::npos)) if (response && (response->size() < 1024 || response->find("<html>") != std::string::npos))
err.msg = hintfmt("%1%\n\nresponse body:\n\n%2%", normaltxt(hf.str()), chomp(*response)); err.msg = hintfmt("%1%\n\nresponse body:\n\n%2%", normaltxt(hf.str()), chomp(*response));
else else
err.msg = hf; err.msg = hf;
} }
bool isUri(const string & s) bool isUri(std::string_view s)
{ {
if (s.compare(0, 8, "channel:") == 0) return true; if (s.compare(0, 8, "channel:") == 0) return true;
size_t pos = s.find("://"); size_t pos = s.find("://");
if (pos == string::npos) return false; if (pos == std::string::npos) return false;
string scheme(s, 0, pos); std::string scheme(s, 0, pos);
return scheme == "http" || scheme == "https" || scheme == "file" || scheme == "channel" || scheme == "git" || scheme == "s3" || scheme == "ssh"; return scheme == "http" || scheme == "https" || scheme == "file" || scheme == "channel" || scheme == "git" || scheme == "s3" || scheme == "ssh";
} }

View file

@ -119,17 +119,17 @@ class FileTransferError : public Error
{ {
public: public:
FileTransfer::Error error; FileTransfer::Error error;
std::optional<string> response; // intentionally optional std::optional<std::string> response; // intentionally optional
template<typename... Args> template<typename... Args>
FileTransferError(FileTransfer::Error error, std::optional<string> response, const Args & ... args); FileTransferError(FileTransfer::Error error, std::optional<std::string> response, const Args & ... args);
virtual const char* sname() const override { return "FileTransferError"; } virtual const char* sname() const override { return "FileTransferError"; }
}; };
bool isUri(const string & s); bool isUri(std::string_view s);
/* Resolve deprecated 'channel:<foo>' URLs. */ /* Resolve deprecated 'channel:<foo>' URLs. */
std::string resolveUri(const std::string & uri); std::string resolveUri(std::string_view uri);
} }

View file

@ -47,9 +47,8 @@ static void makeSymlink(const Path & link, const Path & target)
void LocalStore::addIndirectRoot(const Path & path) void LocalStore::addIndirectRoot(const Path & path)
{ {
string hash = hashString(htSHA1, path).to_string(Base32, false); std::string hash = hashString(htSHA1, path).to_string(Base32, false);
Path realRoot = canonPath((format("%1%/%2%/auto/%3%") Path realRoot = canonPath(fmt("%1%/%2%/auto/%3%", stateDir, gcRootsDir, hash));
% stateDir % gcRootsDir % hash).str());
makeSymlink(realRoot, path); makeSymlink(realRoot, path);
} }
@ -162,7 +161,7 @@ void LocalStore::addTempRoot(const StorePath & path)
} }
/* Append the store path to the temporary roots file. */ /* Append the store path to the temporary roots file. */
string s = printStorePath(path) + '\0'; auto s = printStorePath(path) + '\0';
writeFull(state->fdTempRoots.get(), s); writeFull(state->fdTempRoots.get(), s);
} }
@ -203,12 +202,12 @@ void LocalStore::findTempRoots(Roots & tempRoots, bool censor)
} }
/* Read the entire file. */ /* Read the entire file. */
string contents = readFile(fd.get()); auto contents = readFile(fd.get());
/* Extract the roots. */ /* 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); Path root(contents, pos, end - pos);
debug("got temporary root '%s'", root); debug("got temporary root '%s'", root);
tempRoots[parseStorePath(root)].emplace(censor ? censored : fmt("{temp:%d}", pid)); tempRoots[parseStorePath(root)].emplace(censor ? censored : fmt("{temp:%d}", pid));
@ -305,7 +304,7 @@ Roots LocalStore::findRoots(bool censor)
typedef std::unordered_map<Path, std::unordered_set<std::string>> UncheckedRoots; typedef std::unordered_map<Path, std::unordered_set<std::string>> 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... */ /* 64 is the starting buffer size gnu readlink uses... */
auto bufsiz = ssize_t{64}; auto bufsiz = ssize_t{64};
@ -328,7 +327,7 @@ try_again:
.emplace(file); .emplace(file);
} }
static string quoteRegexChars(const string & raw) static std::string quoteRegexChars(const std::string & raw)
{ {
static auto specialRegex = std::regex(R"([.^$\\*+?()\[\]{}|])"); static auto specialRegex = std::regex(R"([.^$\\*+?()\[\]{}|])");
return std::regex_replace(raw, specialRegex, R"(\$&)"); return std::regex_replace(raw, specialRegex, R"(\$&)");
@ -383,7 +382,7 @@ void LocalStore::findRuntimeRoots(Roots & roots, bool censor)
try { try {
auto mapFile = fmt("/proc/%s/maps", ent->d_name); auto mapFile = fmt("/proc/%s/maps", ent->d_name);
auto mapLines = tokenizeString<std::vector<string>>(readFile(mapFile), "\n"); auto mapLines = tokenizeString<std::vector<std::string>>(readFile(mapFile), "\n");
for (const auto & line : mapLines) { for (const auto & line : mapLines) {
auto match = std::smatch{}; auto match = std::smatch{};
if (std::regex_match(line, match, mapRegex)) if (std::regex_match(line, match, mapRegex))
@ -784,7 +783,7 @@ void LocalStore::collectGarbage(const GCOptions & options, GCResults & results)
struct dirent * dirent; struct dirent * dirent;
while (errno = 0, dirent = readdir(dir.get())) { while (errno = 0, dirent = readdir(dir.get())) {
checkInterrupt(); checkInterrupt();
string name = dirent->d_name; std::string name = dirent->d_name;
if (name == "." || name == ".." || name == linksName) continue; if (name == "." || name == ".." || name == linksName) continue;
if (auto storePath = maybeParseStorePath(storeDir + "/" + name)) if (auto storePath = maybeParseStorePath(storeDir + "/" + name))
@ -825,7 +824,7 @@ void LocalStore::collectGarbage(const GCOptions & options, GCResults & results)
struct dirent * dirent; struct dirent * dirent;
while (errno = 0, dirent = readdir(dir.get())) { while (errno = 0, dirent = readdir(dir.get())) {
checkInterrupt(); checkInterrupt();
string name = dirent->d_name; std::string name = dirent->d_name;
if (name == "." || name == "..") continue; if (name == "." || name == "..") continue;
Path path = linksDir + "/" + name; Path path = linksDir + "/" + name;

View file

@ -100,7 +100,7 @@ std::vector<Path> getUserConfigFiles()
// Use the paths specified in NIX_USER_CONF_FILES if it has been defined // Use the paths specified in NIX_USER_CONF_FILES if it has been defined
auto nixConfFiles = getEnv("NIX_USER_CONF_FILES"); auto nixConfFiles = getEnv("NIX_USER_CONF_FILES");
if (nixConfFiles.has_value()) { if (nixConfFiles.has_value()) {
return tokenizeString<std::vector<string>>(nixConfFiles.value(), ":"); return tokenizeString<std::vector<std::string>>(nixConfFiles.value(), ":");
} }
// Use the paths specified by the XDG spec // Use the paths specified by the XDG spec
@ -181,7 +181,7 @@ bool Settings::isWSL1()
return hasSuffix(utsbuf.release, "-Microsoft"); return hasSuffix(utsbuf.release, "-Microsoft");
} }
const string nixVersion = PACKAGE_VERSION; const std::string nixVersion = PACKAGE_VERSION;
NLOHMANN_JSON_SERIALIZE_ENUM(SandboxMode, { NLOHMANN_JSON_SERIALIZE_ENUM(SandboxMode, {
{SandboxMode::smEnabled, true}, {SandboxMode::smEnabled, true},

View file

@ -988,6 +988,6 @@ void loadConfFile();
// Used by the Settings constructor // Used by the Settings constructor
std::vector<Path> getUserConfigFiles(); std::vector<Path> getUserConfigFiles();
extern const string nixVersion; extern const std::string nixVersion;
} }

View file

@ -48,7 +48,7 @@ struct LegacySSHStore : public virtual LegacySSHStoreConfig, public virtual Stor
static std::set<std::string> uriSchemes() { return {"ssh"}; } static std::set<std::string> 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) : StoreConfig(params)
, LegacySSHStoreConfig(params) , LegacySSHStoreConfig(params)
, Store(params) , Store(params)
@ -107,7 +107,7 @@ struct LegacySSHStore : public virtual LegacySSHStoreConfig, public virtual Stor
return conn; return conn;
}; };
string getUri() override std::string getUri() override
{ {
return *uriSchemes().begin() + "://" + host; return *uriSchemes().begin() + "://" + host;
} }
@ -225,13 +225,21 @@ struct LegacySSHStore : public virtual LegacySSHStoreConfig, public virtual Stor
std::optional<StorePath> queryPathFromHashPart(const std::string & hashPart) override std::optional<StorePath> queryPathFromHashPart(const std::string & hashPart) override
{ unsupported("queryPathFromHashPart"); } { unsupported("queryPathFromHashPart"); }
StorePath addToStore(const string & name, const Path & srcPath, StorePath addToStore(
FileIngestionMethod method, HashType hashAlgo, std::string_view name,
PathFilter & filter, RepairFlag repair, const StorePathSet & references) override const Path & srcPath,
FileIngestionMethod method,
HashType hashAlgo,
PathFilter & filter,
RepairFlag repair,
const StorePathSet & references) override
{ unsupported("addToStore"); } { unsupported("addToStore"); }
StorePath addTextToStore(const string & name, const string & s, StorePath addTextToStore(
const StorePathSet & references, RepairFlag repair) override std::string_view name,
std::string_view s,
const StorePathSet & references,
RepairFlag repair) override
{ unsupported("addTextToStore"); } { unsupported("addTextToStore"); }
private: private:

View file

@ -85,7 +85,7 @@ void LocalFSStore::narFromPath(const StorePath & path, Sink & sink)
dumpPath(getRealStoreDir() + std::string(printStorePath(path), storeDir.size()), sink); dumpPath(getRealStoreDir() + std::string(printStorePath(path), storeDir.size()), sink);
} }
const string LocalFSStore::drvsLogDir = "drvs"; const std::string LocalFSStore::drvsLogDir = "drvs";
std::optional<std::string> LocalFSStore::getBuildLog(const StorePath & path_) std::optional<std::string> LocalFSStore::getBuildLog(const StorePath & path_)
{ {

View file

@ -27,7 +27,7 @@ class LocalFSStore : public virtual LocalFSStoreConfig, public virtual Store
{ {
public: public:
const static string drvsLogDir; const static std::string drvsLogDir;
LocalFSStore(const Params & params); LocalFSStore(const Params & params);

View file

@ -70,7 +70,7 @@ int getSchema(Path schemaPath)
{ {
int curSchema = 0; int curSchema = 0;
if (pathExists(schemaPath)) { if (pathExists(schemaPath)) {
string s = readFile(schemaPath); auto s = readFile(schemaPath);
auto n = string2Int<int>(s); auto n = string2Int<int>(s);
if (!n) if (!n)
throw Error("'%1%' is corrupt", schemaPath); throw Error("'%1%' is corrupt", schemaPath);
@ -239,7 +239,7 @@ LocalStore::LocalStore(const Params & params)
res = posix_fallocate(fd.get(), 0, settings.reservedSize); res = posix_fallocate(fd.get(), 0, settings.reservedSize);
#endif #endif
if (res == -1) { 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); [[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); throw SysError("Nix database directory '%1%' is not writable", dbDir);
/* Open the Nix database. */ /* Open the Nix database. */
string dbPath = dbDir + "/db.sqlite"; std::string dbPath = dbDir + "/db.sqlite";
auto & db(state.db); auto & db(state.db);
state.db = SQLite(dbPath, create); 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 should be safe enough. If the user asks for it, don't sync at
all. This can cause database corruption if the system all. This can cause database corruption if the system
crashes. */ crashes. */
string syncMode = settings.fsyncMetadata ? "normal" : "off"; std::string syncMode = settings.fsyncMetadata ? "normal" : "off";
db.exec("pragma synchronous = " + syncMode); db.exec("pragma synchronous = " + syncMode);
/* Set the SQLite journal mode. WAL mode is fastest, so it's the /* Set the SQLite journal mode. WAL mode is fastest, so it's the
default. */ default. */
string mode = settings.useSQLiteWAL ? "wal" : "truncate"; std::string mode = settings.useSQLiteWAL ? "wal" : "truncate";
string prevMode; std::string prevMode;
{ {
SQLiteStmt stmt; SQLiteStmt stmt;
stmt.create(db, "pragma main.journal_mode;"); stmt.create(db, "pragma main.journal_mode;");
if (sqlite3_step(stmt) != SQLITE_ROW) if (sqlite3_step(stmt) != SQLITE_ROW)
throwSQLiteError(db, "querying journal mode"); 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 && if (prevMode != mode &&
sqlite3_exec(db, ("pragma main.journal_mode = " + mode + ";").c_str(), 0, 0, 0) != SQLITE_OK) 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()); assert(drvPath.isDerivation());
std::string drvName(drvPath.name()); 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) 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<void>([&]() { retrySQLite<void>([&]() {
state.stmts->AddDerivationOutput.use() state.stmts->AddDerivationOutput.use()
@ -795,7 +799,6 @@ void LocalStore::cacheDrvOutputMapping(State & state, const uint64_t deriver, co
(printStorePath(output)) (printStorePath(output))
.exec(); .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) const StorePathSet & references, RepairFlag repair)
{ {
auto hash = hashString(htSHA256, s); auto hash = hashString(htSHA256, s);
@ -1548,7 +1553,7 @@ bool LocalStore::verifyStore(bool checkContents, RepairFlag repair)
for (auto & link : readDirectory(linksDir)) { for (auto & link : readDirectory(linksDir)) {
printMsg(lvlTalkative, "checking contents of '%s'", link.name); printMsg(lvlTalkative, "checking contents of '%s'", link.name);
Path linkPath = linksDir + "/" + 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) { if (hash != link.name) {
printError("link '%s' was modified! expected hash '%s', got '%s'", printError("link '%s' was modified! expected hash '%s', got '%s'",
linkPath, link.name, hash); linkPath, link.name, hash);

View file

@ -147,8 +147,11 @@ public:
StorePath addToStoreFromDump(Source & dump, std::string_view name, StorePath addToStoreFromDump(Source & dump, std::string_view name,
FileIngestionMethod method, HashType hashAlgo, RepairFlag repair, const StorePathSet & references) override; FileIngestionMethod method, HashType hashAlgo, RepairFlag repair, const StorePathSet & references) override;
StorePath addTextToStore(const string & name, const string & s, StorePath addTextToStore(
const StorePathSet & references, RepairFlag repair) override; std::string_view name,
std::string_view s,
const StorePathSet & references,
RepairFlag repair) override;
void addTempRoot(const StorePath & path) override; void addTempRoot(const StorePath & path) override;
@ -204,7 +207,11 @@ public:
derivation 'deriver'. */ derivation 'deriver'. */
void registerDrvOutput(const Realisation & info) override; void registerDrvOutput(const Realisation & info) override;
void registerDrvOutput(const Realisation & info, CheckSigsFlag checkSigs) 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<const Realisation> queryRealisation_(State & state, const DrvOutput & id); std::optional<const Realisation> queryRealisation_(State & state, const DrvOutput & id);
std::optional<std::pair<int64_t, Realisation>> queryRealisationCore_(State & state, const DrvOutput & id); std::optional<std::pair<int64_t, Realisation>> queryRealisationCore_(State & state, const DrvOutput & id);

View file

@ -13,7 +13,7 @@ private:
AutoCloseFD fdUserLock; AutoCloseFD fdUserLock;
bool isEnabled = false; bool isEnabled = false;
string user; std::string user;
uid_t uid = 0; uid_t uid = 0;
gid_t gid = 0; gid_t gid = 0;
std::vector<gid_t> supplementaryGIDs; std::vector<gid_t> supplementaryGIDs;
@ -23,7 +23,7 @@ public:
void kill(); void kill();
string getUser() { return user; } std::string getUser() { return user; }
uid_t getUID() { assert(uid); return uid; } uid_t getUID() { assert(uid); return uid; }
uid_t getGID() { assert(gid); return gid; } uid_t getGID() { assert(gid); return gid; }
std::vector<gid_t> getSupplementaryGIDs() { return supplementaryGIDs; } std::vector<gid_t> getSupplementaryGIDs() { return supplementaryGIDs; }

View file

@ -39,19 +39,19 @@ Machine::Machine(decltype(storeUri) storeUri,
sshPublicHostKey(sshPublicHostKey) sshPublicHostKey(sshPublicHostKey)
{} {}
bool Machine::allSupported(const std::set<string> & features) const bool Machine::allSupported(const std::set<std::string> & features) const
{ {
return std::all_of(features.begin(), features.end(), return std::all_of(features.begin(), features.end(),
[&](const string & feature) { [&](const std::string & feature) {
return supportedFeatures.count(feature) || return supportedFeatures.count(feature) ||
mandatoryFeatures.count(feature); mandatoryFeatures.count(feature);
}); });
} }
bool Machine::mandatoryMet(const std::set<string> & features) const bool Machine::mandatoryMet(const std::set<std::string> & features) const
{ {
return std::all_of(mandatoryFeatures.begin(), mandatoryFeatures.end(), return std::all_of(mandatoryFeatures.begin(), mandatoryFeatures.end(),
[&](const string & feature) { [&](const std::string & feature) {
return features.count(feature); return features.count(feature);
}); });
} }
@ -89,7 +89,7 @@ ref<Store> Machine::openStore() const
static std::vector<std::string> expandBuilderLines(const std::string & builders) static std::vector<std::string> expandBuilderLines(const std::string & builders)
{ {
std::vector<std::string> result; std::vector<std::string> result;
for (auto line : tokenizeString<std::vector<string>>(builders, "\n;")) { for (auto line : tokenizeString<std::vector<std::string>>(builders, "\n;")) {
trim(line); trim(line);
line.erase(std::find(line.begin(), line.end(), '#'), line.end()); line.erase(std::find(line.begin(), line.end(), '#'), line.end());
if (line.empty()) continue; if (line.empty()) continue;
@ -117,7 +117,7 @@ static std::vector<std::string> expandBuilderLines(const std::string & builders)
static Machine parseBuilderLine(const std::string & line) static Machine parseBuilderLine(const std::string & line)
{ {
const auto tokens = tokenizeString<std::vector<string>>(line); const auto tokens = tokenizeString<std::vector<std::string>>(line);
auto isSet = [&](size_t fieldIndex) { auto isSet = [&](size_t fieldIndex) {
return tokens.size() > fieldIndex && tokens[fieldIndex] != "" && tokens[fieldIndex] != "-"; return tokens.size() > fieldIndex && tokens[fieldIndex] != "" && tokens[fieldIndex] != "-";
@ -146,17 +146,18 @@ static Machine parseBuilderLine(const std::string & line)
return { return {
tokens[0], tokens[0],
isSet(1) ? tokenizeString<std::vector<string>>(tokens[1], ",") : std::vector<string>{settings.thisSystem}, isSet(1) ? tokenizeString<std::vector<std::string>>(tokens[1], ",") : std::vector<std::string>{settings.thisSystem},
isSet(2) ? tokens[2] : "", isSet(2) ? tokens[2] : "",
isSet(3) ? parseUnsignedIntField(3) : 1U, isSet(3) ? parseUnsignedIntField(3) : 1U,
isSet(4) ? parseUnsignedIntField(4) : 1U, isSet(4) ? parseUnsignedIntField(4) : 1U,
isSet(5) ? tokenizeString<std::set<string>>(tokens[5], ",") : std::set<string>{}, isSet(5) ? tokenizeString<std::set<std::string>>(tokens[5], ",") : std::set<std::string>{},
isSet(6) ? tokenizeString<std::set<string>>(tokens[6], ",") : std::set<string>{}, isSet(6) ? tokenizeString<std::set<std::string>>(tokens[6], ",") : std::set<std::string>{},
isSet(7) ? ensureBase64(7) : "" isSet(7) ? ensureBase64(7) : ""
}; };
} }
static Machines parseBuilderLines(const std::vector<std::string>& builders) { static Machines parseBuilderLines(const std::vector<std::string> & builders)
{
Machines result; Machines result;
std::transform(builders.begin(), builders.end(), std::back_inserter(result), parseBuilderLine); std::transform(builders.begin(), builders.end(), std::back_inserter(result), parseBuilderLine);
return result; return result;

View file

@ -90,7 +90,7 @@ struct NarAccessor : public FSAccessor
void receiveContents(std::string_view data) override 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, createMember(path,
NarMember{FSAccessor::Type::tSymlink, false, 0, 0, target}); NarMember{FSAccessor::Type::tSymlink, false, 0, 0, target});

View file

@ -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); return Error("NAR info file '%1%' is corrupt", whence);
}; };
auto parseHashField = [&](const string & s) { auto parseHashField = [&](const std::string & s) {
try { try {
return Hash::parseAnyPrefixed(s); return Hash::parseAnyPrefixed(s);
} catch (BadHash &) { } catch (BadHash &) {

View file

@ -77,7 +77,7 @@ Strings LocalStore::readDirectoryIgnoringInodes(const Path & path, const InodeHa
continue; continue;
} }
string name = dirent->d_name; std::string name = dirent->d_name;
if (name == "." || name == "..") continue; if (name == "." || name == "..") continue;
names.push_back(name); names.push_back(name);
} }

View file

@ -49,9 +49,9 @@ std::pair<std::string_view, StringSet> parsePathWithOutputs(std::string_view s)
{ {
size_t n = s.find("!"); size_t n = s.find("!");
return n == s.npos return n == s.npos
? std::make_pair(s, std::set<string>()) ? std::make_pair(s, std::set<std::string>())
: std::make_pair(((std::string_view) s).substr(0, n), : std::make_pair(((std::string_view) s).substr(0, n),
tokenizeString<std::set<string>>(((std::string_view) s).substr(n + 1), ",")); tokenizeString<std::set<std::string>>(((std::string_view) s).substr(n + 1), ","));
} }

View file

@ -62,7 +62,7 @@ public:
typedef std::set<StorePath> StorePathSet; typedef std::set<StorePath> StorePathSet;
typedef std::vector<StorePath> StorePaths; typedef std::vector<StorePath> StorePaths;
typedef std::map<string, StorePath> OutputPathMap; typedef std::map<std::string, StorePath> OutputPathMap;
typedef std::map<StorePath, std::optional<ContentAddress>> StorePathCAMap; typedef std::map<StorePath, std::optional<ContentAddress>> StorePathCAMap;

View file

@ -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) : deletePaths(false)
{ {
lockPaths(paths, waitMsg); lockPaths(paths, waitMsg);
@ -82,7 +82,7 @@ PathLocks::PathLocks(const PathSet & paths, const string & waitMsg)
bool PathLocks::lockPaths(const PathSet & paths, bool PathLocks::lockPaths(const PathSet & paths,
const string & waitMsg, bool wait) const std::string & waitMsg, bool wait)
{ {
assert(fds.empty()); assert(fds.empty());

View file

@ -26,9 +26,9 @@ private:
public: public:
PathLocks(); PathLocks();
PathLocks(const PathSet & paths, PathLocks(const PathSet & paths,
const string & waitMsg = ""); const std::string & waitMsg = "");
bool lockPaths(const PathSet & _paths, bool lockPaths(const PathSet & _paths,
const string & waitMsg = "", const std::string & waitMsg = "",
bool wait = true); bool wait = true);
~PathLocks(); ~PathLocks();
void unlock(); void unlock();

View file

@ -15,12 +15,12 @@ namespace nix {
/* Parse a generation name of the format /* Parse a generation name of the format
`<profilename>-<number>-link'. */ `<profilename>-<number>-link'. */
static std::optional<GenerationNumber> parseName(const string & profileName, const string & name) static std::optional<GenerationNumber> parseName(const std::string & profileName, const std::string & name)
{ {
if (string(name, 0, profileName.size() + 1) != profileName + "-") return {}; if (name.substr(0, profileName.size() + 1) != profileName + "-") return {};
string s = string(name, profileName.size() + 1); auto s = name.substr(profileName.size() + 1);
string::size_type p = s.find("-link"); auto p = s.find("-link");
if (p == string::npos) return {}; if (p == std::string::npos) return {};
if (auto n = string2Int<unsigned int>(s.substr(0, p))) if (auto n = string2Int<unsigned int>(s.substr(0, p)))
return *n; return *n;
else 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') if (timeSpec.empty() || timeSpec[timeSpec.size() - 1] != 'd')
throw UsageError("invalid number of days specifier '%1%', expected something like '14d'", timeSpec); throw UsageError("invalid number of days specifier '%1%', expected something like '14d'", timeSpec);
time_t curTime = time(0); time_t curTime = time(0);
string strDays = string(timeSpec, 0, timeSpec.size() - 1); auto strDays = timeSpec.substr(0, timeSpec.size() - 1);
auto days = string2Int<int>(strDays); auto days = string2Int<int>(strDays);
if (!days || *days < 1) 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) : ""; return pathExists(profile) ? readLink(profile) : "";
} }

View file

@ -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, 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); 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 generally cheap, since the build results are still in the Nix
store. Most of the time, only the user environment has to be store. Most of the time, only the user environment has to be
rebuilt. */ rebuilt. */
string optimisticLockProfile(const Path & profile); std::string optimisticLockProfile(const Path & profile);
/* Resolve ~/.nix-profile. If ~/.nix-profile doesn't exist yet, create /* Resolve ~/.nix-profile. If ~/.nix-profile doesn't exist yet, create
it. */ it. */

View file

@ -68,7 +68,7 @@ void RefScanSink::operator () (std::string_view data)
std::pair<StorePathSet, HashResult> scanForReferences( std::pair<StorePathSet, HashResult> scanForReferences(
const string & path, const std::string & path,
const StorePathSet & refs) const StorePathSet & refs)
{ {
HashSink hashSink { htSHA256 }; HashSink hashSink { htSHA256 };
@ -121,7 +121,7 @@ void RewritingSink::operator () (std::string_view data)
s.append(data); s.append(data);
size_t j = 0; 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); matches.push_back(pos + j);
s.replace(j, from.size(), to); s.replace(j, from.size(), to);
} }

View file

@ -661,8 +661,11 @@ void RemoteStore::addMultipleToStore(
} }
StorePath RemoteStore::addTextToStore(const string & name, const string & s, StorePath RemoteStore::addTextToStore(
const StorePathSet & references, RepairFlag repair) std::string_view name,
std::string_view s,
const StorePathSet & references,
RepairFlag repair)
{ {
StringSource source(s); StringSource source(s);
return addCAToStore(source, name, TextHashMethod{}, references, repair)->path; return addCAToStore(source, name, TextHashMethod{}, references, repair)->path;
@ -1000,7 +1003,7 @@ std::exception_ptr RemoteStore::Connection::processStderr(Sink * sink, Source *
auto msg = readNum<uint64_t>(from); auto msg = readNum<uint64_t>(from);
if (msg == STDERR_WRITE) { if (msg == STDERR_WRITE) {
string s = readString(from); auto s = readString(from);
if (!sink) throw Error("no sink"); if (!sink) throw Error("no sink");
(*sink)(s); (*sink)(s);
} }
@ -1017,7 +1020,7 @@ std::exception_ptr RemoteStore::Connection::processStderr(Sink * sink, Source *
if (GET_PROTOCOL_MINOR(daemonVersion) >= 26) { if (GET_PROTOCOL_MINOR(daemonVersion) >= 26) {
return std::make_exception_ptr(readError(from)); return std::make_exception_ptr(readError(from));
} else { } else {
string error = readString(from); auto error = readString(from);
unsigned int status = readInt(from); unsigned int status = readInt(from);
return std::make_exception_ptr(Error(status, error)); return std::make_exception_ptr(Error(status, error));
} }

View file

@ -83,8 +83,11 @@ public:
RepairFlag repair, RepairFlag repair,
CheckSigsFlag checkSigs) override; CheckSigsFlag checkSigs) override;
StorePath addTextToStore(const string & name, const string & s, StorePath addTextToStore(
const StorePathSet & references, RepairFlag repair) override; std::string_view name,
std::string_view s,
const StorePathSet & references,
RepairFlag repair) override;
void registerDrvOutput(const Realisation & info) override; void registerDrvOutput(const Realisation & info) override;

View file

@ -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)) : config(makeConfig(region, scheme, endpoint))
, client(make_ref<Aws::S3::S3Client>( , client(make_ref<Aws::S3::S3Client>(
profile == "" profile == ""
@ -121,7 +125,10 @@ class RetryStrategy : public Aws::Client::DefaultRetryStrategy
} }
}; };
ref<Aws::Client::ClientConfiguration> S3Helper::makeConfig(const string & region, const string & scheme, const string & endpoint) ref<Aws::Client::ClientConfiguration> S3Helper::makeConfig(
const std::string & region,
const std::string & scheme,
const std::string & endpoint)
{ {
initAWS(); initAWS();
auto res = make_ref<Aws::Client::ClientConfiguration>(); auto res = make_ref<Aws::Client::ClientConfiguration>();

View file

@ -71,7 +71,7 @@ uint64_t SQLite::getLastInsertedRowId()
return sqlite3_last_insert_rowid(db); return sqlite3_last_insert_rowid(db);
} }
void SQLiteStmt::create(sqlite3 * db, const string & sql) void SQLiteStmt::create(sqlite3 * db, const std::string & sql)
{ {
checkInterrupt(); checkInterrupt();
assert(!stmt); assert(!stmt);

View file

@ -29,7 +29,7 @@ void SSHMaster::addCommonSSHOpts(Strings & args)
if (!sshPublicHostKey.empty()) { if (!sshPublicHostKey.empty()) {
Path fileName = (Path) *state->tmpDir + "/host-key"; Path fileName = (Path) *state->tmpDir + "/host-key";
auto p = host.rfind("@"); 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"); writeFile(fileName, thost + " " + base64Decode(sshPublicHostKey) + "\n");
args.insert(args.end(), {"-oUserKnownHostsFile=" + fileName}); args.insert(args.end(), {"-oUserKnownHostsFile=" + fileName});
} }

View file

@ -39,7 +39,7 @@ Path Store::followLinksToStore(std::string_view _path) const
Path path = absPath(std::string(_path)); Path path = absPath(std::string(_path));
while (!isInStore(path)) { while (!isInStore(path)) {
if (!isLink(path)) break; if (!isLink(path)) break;
string target = readLink(path); auto target = readLink(path);
path = absPath(target, dirOf(path)); path = absPath(target, dirOf(path));
} }
if (!isInStore(path)) if (!isInStore(path))
@ -138,8 +138,8 @@ StorePath Store::makeStorePath(std::string_view type,
std::string_view hash, std::string_view name) const std::string_view hash, std::string_view name) const
{ {
/* e.g., "source:sha256:1abc...:/nix/store:foo.tar.gz" */ /* e.g., "source:sha256:1abc...:/nix/store:foo.tar.gz" */
string s = std::string { type } + ":" + std::string { hash } auto s = std::string(type) + ":" + std::string(hash)
+ ":" + storeDir + ":" + std::string { name }; + ":" + storeDir + ":" + std::string(name);
auto h = compressHash(hashString(htSHA256, s), 20); auto h = compressHash(hashString(htSHA256, s), 20);
return StorePath(h, name); return StorePath(h, name);
} }
@ -161,7 +161,7 @@ StorePath Store::makeOutputPath(std::string_view id,
static std::string makeType( static std::string makeType(
const Store & store, const Store & store,
string && type, std::string && type,
const StorePathSet & references, const StorePathSet & references,
bool hasSelfReference = false) bool hasSelfReference = false)
{ {
@ -229,15 +229,23 @@ std::pair<StorePath, Hash> 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 const StorePathSet & references) const
{ {
return makeTextPath(name, hashString(htSHA256, s), references); return makeTextPath(name, hashString(htSHA256, s), references);
} }
StorePath Store::addToStore(const string & name, const Path & _srcPath, StorePath Store::addToStore(
FileIngestionMethod method, HashType hashAlgo, PathFilter & filter, RepairFlag repair, const StorePathSet & references) std::string_view name,
const Path & _srcPath,
FileIngestionMethod method,
HashType hashAlgo,
PathFilter & filter,
RepairFlag repair,
const StorePathSet & references)
{ {
Path srcPath(absPath(_srcPath)); Path srcPath(absPath(_srcPath));
auto source = sinkToSource([&](Sink & sink) { auto source = sinkToSource([&](Sink & sink) {
@ -688,10 +696,10 @@ StorePathSet Store::queryValidPaths(const StorePathSet & paths, SubstituteFlag m
/* Return a string accepted by decodeValidPathInfo() that /* Return a string accepted by decodeValidPathInfo() that
registers the specified paths as valid. Note: it's the registers the specified paths as valid. Note: it's the
responsibility of the caller to provide a closure. */ 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) bool showDerivers, bool showHash)
{ {
string s = ""; std::string s = "";
for (auto & i : paths) { for (auto & i : paths) {
s += printStorePath(i) + "\n"; s += printStorePath(i) + "\n";
@ -1131,7 +1139,7 @@ std::optional<ValidPathInfo> decodeValidPathInfo(const Store & store, std::istre
getline(str, path); getline(str, path);
if (str.eof()) { return {}; } if (str.eof()) { return {}; }
if (!hashGiven) { if (!hashGiven) {
string s; std::string s;
getline(str, s); getline(str, s);
auto narHash = Hash::parseAny(s, htSHA256); auto narHash = Hash::parseAny(s, htSHA256);
getline(str, s); getline(str, s);
@ -1144,7 +1152,7 @@ std::optional<ValidPathInfo> decodeValidPathInfo(const Store & store, std::istre
std::string deriver; std::string deriver;
getline(str, deriver); getline(str, deriver);
if (deriver != "") info.deriver = store.parseStorePath(deriver); if (deriver != "") info.deriver = store.parseStorePath(deriver);
string s; std::string s;
getline(str, s); getline(str, s);
auto n = string2Int<int>(s); auto n = string2Int<int>(s);
if (!n) throw Error("number expected"); 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)); return concatStringsSep(", ", quoteStrings(paths));
} }

View file

@ -352,7 +352,9 @@ public:
simply yield a different store path, so other users wouldn't be simply yield a different store path, so other users wouldn't be
affected), but it has some backwards compatibility issues (the affected), but it has some backwards compatibility issues (the
hashing scheme changes), so I'm not doing that for now. */ 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; const StorePathSet & references) const;
/* Check whether a path is valid. */ /* Check whether a path is valid. */
@ -482,9 +484,14 @@ public:
validity the resulting path. The resulting path is returned. validity the resulting path. The resulting path is returned.
The function object `filter' can be used to exclude files (see The function object `filter' can be used to exclude files (see
libutil/archive.hh). */ libutil/archive.hh). */
virtual StorePath addToStore(const string & name, const Path & srcPath, virtual StorePath addToStore(
FileIngestionMethod method = FileIngestionMethod::Recursive, HashType hashAlgo = htSHA256, std::string_view name,
PathFilter & filter = defaultPathFilter, RepairFlag repair = NoRepair, const StorePathSet & references = StorePathSet()); 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 /* Copy the contents of a path to the store and register the
validity the resulting path, using a constant amount of 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 /* Like addToStore, but the contents written to the output path is
a regular file containing the given string. */ a regular file containing the given string. */
virtual StorePath addTextToStore(const string & name, const string & s, virtual StorePath addTextToStore(
const StorePathSet & references, RepairFlag repair = NoRepair) = 0; 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 * 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 /* Return a string representing information about the path that
can be loaded into the database using `nix-store --load-db' or can be loaded into the database using `nix-store --load-db' or
`nix-store --register-validity'. */ `nix-store --register-validity'. */
string makeValidityRegistration(const StorePathSet & paths, std::string makeValidityRegistration(const StorePathSet & paths,
bool showDerivers, bool showHash); bool showDerivers, bool showHash);
/* Write a JSON representation of store path metadata, such as the /* 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 /* Display a set of paths in human-readable form (i.e., between quotes
and separated by commas). */ and separated by commas). */
string showPaths(const PathSet & paths); std::string showPaths(const PathSet & paths);
std::optional<ValidPathInfo> decodeValidPathInfo( std::optional<ValidPathInfo> decodeValidPathInfo(

View file

@ -37,7 +37,7 @@ static GlobalConfig::Register rArchiveSettings(&archiveSettings);
const std::string narVersionMagic1 = "nix-archive-1"; 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; }; 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 /* If we're on a case-insensitive system like macOS, undo
the case hack applied by restorePath(). */ the case hack applied by restorePath(). */
std::map<string, string> unhacked; std::map<std::string, std::string> unhacked;
for (auto & i : readDirectory(path)) for (auto & i : readDirectory(path))
if (archiveSettings.useCaseHack) { if (archiveSettings.useCaseHack) {
string name(i.name); std::string name(i.name);
size_t pos = i.name.find(caseHackSuffix); 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)); debug(format("removing case hack suffix from '%1%'") % (path + "/" + i.name));
name.erase(pos); 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 << ")"; sink << narVersionMagic1 << "(" << "type" << "regular" << "contents" << s << ")";
} }
static SerialisationError badArchive(string s) static SerialisationError badArchive(const std::string & s)
{ {
return SerialisationError("bad archive: " + s); return SerialisationError("bad archive: " + s);
} }
@ -171,7 +171,7 @@ static void parseContents(ParseSink & sink, Source & source, const Path & path)
struct CaseInsensitiveCompare 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; 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) static void parse(ParseSink & sink, Source & source, const Path & path)
{ {
string s; std::string s;
s = readString(source); s = readString(source);
if (s != "(") throw badArchive("expected open tag"); 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") { else if (s == "type") {
if (type != tpUnknown) if (type != tpUnknown)
throw badArchive("multiple type fields"); throw badArchive("multiple type fields");
string t = readString(source); std::string t = readString(source);
if (t == "regular") { if (t == "regular") {
type = tpRegular; type = tpRegular;
@ -232,7 +232,7 @@ static void parse(ParseSink & sink, Source & source, const Path & path)
} }
else if (s == "entry" && type == tpDirectory) { else if (s == "entry" && type == tpDirectory) {
string name, prevName; std::string name, prevName;
s = readString(source); s = readString(source);
if (s != "(") throw badArchive("expected open tag"); if (s != "(") throw badArchive("expected open tag");
@ -246,7 +246,7 @@ static void parse(ParseSink & sink, Source & source, const Path & path)
break; break;
} else if (s == "name") { } else if (s == "name") {
name = readString(source); 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); throw Error("NAR contains invalid file name '%1%'", name);
if (name <= prevName) if (name <= prevName)
throw Error("NAR directory is not sorted"); 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) { else if (s == "target" && type == tpSymlink) {
string target = readString(source); std::string target = readString(source);
sink.createSymlink(path, target); sink.createSymlink(path, target);
} }
@ -281,7 +281,7 @@ static void parse(ParseSink & sink, Source & source, const Path & path)
void parseDump(ParseSink & sink, Source & source) void parseDump(ParseSink & sink, Source & source)
{ {
string version; std::string version;
try { try {
version = readString(source, narVersionMagic1.size()); version = readString(source, narVersionMagic1.size());
} catch (SerialisationError & e) { } catch (SerialisationError & e) {
@ -345,7 +345,7 @@ struct RestoreSink : ParseSink
writeFull(fd.get(), data); 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; Path p = dstPath + path;
nix::createSymlink(target, p); nix::createSymlink(target, p);

View file

@ -48,7 +48,7 @@ namespace nix {
void dumpPath(const Path & path, Sink & sink, void dumpPath(const Path & path, Sink & sink,
PathFilter & filter = defaultPathFilter); 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. */ /* FIXME: fix this API, it sucks. */
struct ParseSink struct ParseSink
@ -60,7 +60,7 @@ struct ParseSink
virtual void preallocateContents(uint64_t size) { }; virtual void preallocateContents(uint64_t size) { };
virtual void receiveContents(std::string_view data) { }; 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 /* If the NAR archive contains a single file at top-level, then save
@ -82,7 +82,7 @@ struct RetrieveRegularNARSink : ParseSink
sink(data); sink(data);
} }
void createSymlink(const Path & path, const string & target) override void createSymlink(const Path & path, const std::string & target) override
{ {
regular = false; regular = false;
} }

View file

@ -76,13 +76,13 @@ void Args::parseCmdline(const Strings & _cmdline)
/* Expand compound dash options (i.e., `-qlf' -> `-q -l -f', /* Expand compound dash options (i.e., `-qlf' -> `-q -l -f',
`-j3` -> `-j 3`). */ `-j3` -> `-j 3`). */
if (!dashDash && arg.length() > 2 && arg[0] == '-' && arg[1] != '-' && isalpha(arg[1])) { 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; auto next = pos; ++next;
for (unsigned int j = 2; j < arg.length(); j++) for (unsigned int j = 2; j < arg.length(); j++)
if (isalpha(arg[j])) if (isalpha(arg[j]))
cmdline.insert(next, (string) "-" + arg[j]); cmdline.insert(next, (std::string) "-" + arg[j]);
else { else {
cmdline.insert(next, string(arg, j)); cmdline.insert(next, std::string(arg, j));
break; break;
} }
arg = *pos; arg = *pos;
@ -139,7 +139,7 @@ bool Args::processFlag(Strings::iterator & pos, Strings::iterator end)
return true; return true;
}; };
if (string(*pos, 0, 2) == "--") { if (std::string(*pos, 0, 2) == "--") {
if (auto prefix = needsCompletion(*pos)) { if (auto prefix = needsCompletion(*pos)) {
for (auto & [name, flag] : longFlags) { for (auto & [name, flag] : longFlags) {
if (!hiddenCategories.count(flag->category) if (!hiddenCategories.count(flag->category)
@ -147,12 +147,12 @@ bool Args::processFlag(Strings::iterator & pos, Strings::iterator end)
completions->add("--" + name, flag->description); 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; if (i == longFlags.end()) return false;
return process("--" + i->first, *i->second); 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 c = (*pos)[1];
auto i = shortFlags.find(c); auto i = shortFlags.find(c);
if (i == shortFlags.end()) return false; if (i == shortFlags.end()) return false;

View file

@ -158,7 +158,7 @@ public:
} }
/* Expect a string argument. */ /* 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({ expectArgs({
.label = label, .label = label,

View file

@ -81,16 +81,16 @@ void AbstractConfig::applyConfig(const std::string & contents, const std::string
unsigned int pos = 0; unsigned int pos = 0;
while (pos < contents.size()) { while (pos < contents.size()) {
string line; std::string line;
while (pos < contents.size() && contents[pos] != '\n') while (pos < contents.size() && contents[pos] != '\n')
line += contents[pos++]; line += contents[pos++];
pos++; pos++;
string::size_type hash = line.find('#'); auto hash = line.find('#');
if (hash != string::npos) if (hash != std::string::npos)
line = string(line, 0, hash); line = std::string(line, 0, hash);
auto tokens = tokenizeString<std::vector<string>>(line); auto tokens = tokenizeString<std::vector<std::string>>(line);
if (tokens.empty()) continue; if (tokens.empty()) continue;
if (tokens.size() < 2) if (tokens.size() < 2)
@ -120,7 +120,7 @@ void AbstractConfig::applyConfig(const std::string & contents, const std::string
if (tokens[1] != "=") if (tokens[1] != "=")
throw UsageError("illegal configuration line '%1%' in '%2%'", line, path); throw UsageError("illegal configuration line '%1%' in '%2%'", line, path);
string name = tokens[0]; std::string name = tokens[0];
auto i = tokens.begin(); auto i = tokens.begin();
advance(i, 2); advance(i, 2);
@ -132,7 +132,7 @@ void AbstractConfig::applyConfig(const std::string & contents, const std::string
void AbstractConfig::applyConfigFile(const Path & path) void AbstractConfig::applyConfigFile(const Path & path)
{ {
try { try {
string contents = readFile(path); std::string contents = readFile(path);
applyConfig(contents, path); applyConfig(contents, path);
} catch (SysError &) { } } catch (SysError &) { }
} }

View file

@ -17,7 +17,7 @@ BaseError & BaseError::addTrace(std::optional<ErrPos> e, hintformat hint)
// c++ std::exception descendants must have a 'const char* what()' function. // 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(). // 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()) if (what_.has_value())
return *what_; return *what_;
@ -32,14 +32,14 @@ const string & BaseError::calcWhat() const
} }
} }
std::optional<string> ErrorInfo::programName = std::nullopt; std::optional<std::string> ErrorInfo::programName = std::nullopt;
std::ostream & operator<<(std::ostream & os, const hintformat & hf) std::ostream & operator<<(std::ostream & os, const hintformat & hf)
{ {
return os << hf.str(); return os << hf.str();
} }
string showErrPos(const ErrPos & errPos) std::string showErrPos(const ErrPos & errPos)
{ {
if (errPos.line > 0) { if (errPos.line > 0) {
if (errPos.column > 0) { if (errPos.column > 0) {
@ -68,7 +68,7 @@ std::optional<LinesOfCode> getCodeLines(const ErrPos & errPos)
// count the newlines. // count the newlines.
int count = 0; int count = 0;
string line; std::string line;
int pl = errPos.line - 1; int pl = errPos.line - 1;
do do
{ {
@ -100,7 +100,7 @@ std::optional<LinesOfCode> getCodeLines(const ErrPos & errPos)
std::istringstream iss(errPos.file); std::istringstream iss(errPos.file);
// count the newlines. // count the newlines.
int count = 0; int count = 0;
string line; std::string line;
int pl = errPos.line - 1; int pl = errPos.line - 1;
LinesOfCode loc; LinesOfCode loc;
@ -132,7 +132,7 @@ std::optional<LinesOfCode> getCodeLines(const ErrPos & errPos)
// print lines of code to the ostream, indicating the error column. // print lines of code to the ostream, indicating the error column.
void printCodeLines(std::ostream & out, void printCodeLines(std::ostream & out,
const string & prefix, const std::string & prefix,
const ErrPos & errPos, const ErrPos & errPos,
const LinesOfCode & loc) const LinesOfCode & loc)
{ {

View file

@ -61,16 +61,16 @@ typedef enum {
// the lines of code surrounding an error. // the lines of code surrounding an error.
struct LinesOfCode { struct LinesOfCode {
std::optional<string> prevLineOfCode; std::optional<std::string> prevLineOfCode;
std::optional<string> errLineOfCode; std::optional<std::string> errLineOfCode;
std::optional<string> nextLineOfCode; std::optional<std::string> nextLineOfCode;
}; };
// ErrPos indicates the location of an error in a nix file. // ErrPos indicates the location of an error in a nix file.
struct ErrPos { struct ErrPos {
int line = 0; int line = 0;
int column = 0; int column = 0;
string file; std::string file;
FileOrigin origin; FileOrigin origin;
operator bool() const operator bool() const
@ -107,12 +107,12 @@ struct Trace {
struct ErrorInfo { struct ErrorInfo {
Verbosity level; Verbosity level;
string name; // FIXME: rename std::string name; // FIXME: rename
hintformat msg; hintformat msg;
std::optional<ErrPos> errPos; std::optional<ErrPos> errPos;
std::list<Trace> traces; std::list<Trace> traces;
static std::optional<string> programName; static std::optional<std::string> programName;
}; };
std::ostream & showErrorInfo(std::ostream & out, const ErrorInfo & einfo, bool showTrace); std::ostream & showErrorInfo(std::ostream & out, const ErrorInfo & einfo, bool showTrace);
@ -124,8 +124,8 @@ class BaseError : public std::exception
protected: protected:
mutable ErrorInfo err; mutable ErrorInfo err;
mutable std::optional<string> what_; mutable std::optional<std::string> what_;
const string& calcWhat() const; const std::string & calcWhat() const;
public: public:
unsigned int status = 1; // exit status unsigned int status = 1; // exit status
@ -162,11 +162,11 @@ public:
const char * what() const noexcept override { return calcWhat().c_str(); } const char * what() const noexcept override { return calcWhat().c_str(); }
#endif #endif
const string & msg() const { return calcWhat(); } const std::string & msg() const { return calcWhat(); }
const ErrorInfo & info() const { calcWhat(); return err; } const ErrorInfo & info() const { calcWhat(); return err; }
template<typename... Args> template<typename... Args>
BaseError & addTrace(std::optional<ErrPos> e, const string &fs, const Args & ... args) BaseError & addTrace(std::optional<ErrPos> e, const std::string & fs, const Args & ... args)
{ {
return addTrace(e, hintfmt(fs, args...)); return addTrace(e, hintfmt(fs, args...));
} }

View file

@ -10,7 +10,6 @@ namespace nix {
/* Inherit some names from other namespaces for convenience. */ /* Inherit some names from other namespaces for convenience. */
using std::string;
using boost::format; using boost::format;
@ -21,8 +20,8 @@ struct nop { template<typename... T> nop(T...) {} };
struct FormatOrString struct FormatOrString
{ {
string s; std::string s;
FormatOrString(const string & s) : s(s) { }; FormatOrString(std::string s) : s(std::move(s)) { };
template<class F> template<class F>
FormatOrString(const F & f) : s(f.str()) { }; FormatOrString(const F & f) : s(f.str()) { };
FormatOrString(const char * s) : s(s) { }; FormatOrString(const char * s) : s(s) { };
@ -102,7 +101,7 @@ std::ostream & operator<<(std::ostream & out, const normaltxt<T> & y)
class hintformat class hintformat
{ {
public: public:
hintformat(const string & format) : fmt(format) hintformat(const std::string & format) : fmt(format)
{ {
fmt.exceptions(boost::io::all_error_bits ^ fmt.exceptions(boost::io::all_error_bits ^
boost::io::too_many_args_bit ^ boost::io::too_many_args_bit ^

View file

@ -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]; char buf[hash.hashSize * 2];
for (unsigned int i = 0; i < hash.hashSize; i++) { for (unsigned int i = 0; i < hash.hashSize; i++) {
buf[i * 2] = base16Chars[hash.hash[i] >> 4]; buf[i * 2] = base16Chars[hash.hash[i] >> 4];
buf[i * 2 + 1] = base16Chars[hash.hash[i] & 0x0f]; 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 // 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); assert(hash.hashSize);
size_t len = hash.base32Len(); size_t len = hash.base32Len();
assert(len); assert(len);
string s; std::string s;
s.reserve(len); s.reserve(len);
for (int n = (int) len - 1; n >= 0; n--) { 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); assert(hash.type);
return hash.to_string(hash.type == htMD5 ? Base16 : Base32, false); 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 // Mutates the string to eliminate the prefixes when found
static std::pair<std::optional<HashType>, bool> getParsedTypeAndSRI(std::string_view & rest) { static std::pair<std::optional<HashType>, bool> getParsedTypeAndSRI(std::string_view & rest)
{
bool isSRI = false; bool isSRI = false;
// Parse the has type before the separater, if there was one. // 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); throw UsageError("unknown hash algorithm '%1%'", s);
} }
string printHashType(HashType ht) std::string printHashType(HashType ht)
{ {
switch (ht) { switch (ht) {
case htMD5: return "md5"; case htMD5: return "md5";

View file

@ -20,7 +20,7 @@ const int sha512HashSize = 64;
extern std::set<std::string> hashTypes; extern std::set<std::string> hashTypes;
extern const string base32Chars; extern const std::string base32Chars;
enum Base : int { Base64, Base32, Base16, SRI }; enum Base : int { Base64, Base32, Base16, SRI };
@ -110,7 +110,7 @@ public:
Hash newHashAllowEmpty(std::string_view hashStr, std::optional<HashType> ht); Hash newHashAllowEmpty(std::string_view hashStr, std::optional<HashType> ht);
/* Print a hash in base-16 if it's MD5, or base-32 otherwise. */ /* 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. */ /* Compute the hash of the given string. */
Hash hashString(HashType ht, std::string_view s); Hash hashString(HashType ht, std::string_view s);
@ -135,7 +135,7 @@ HashType parseHashType(std::string_view s);
std::optional<HashType> parseHashTypeOpt(std::string_view s); std::optional<HashType> parseHashTypeOpt(std::string_view s);
/* And the reverse. */ /* And the reverse. */
string printHashType(HashType ht); std::string printHashType(HashType ht);
union Ctx; union Ctx;

View file

@ -113,7 +113,7 @@ void warnOnce(bool & haveWarned, const FormatOrString & fs)
} }
} }
void writeToStderr(const string & s) void writeToStderr(std::string_view s)
{ {
try { try {
writeFull(STDERR_FILENO, s, false); writeFull(STDERR_FILENO, s, false);

View file

@ -216,6 +216,6 @@ inline void warn(const std::string & fs, const Args & ... args)
void warnOnce(bool & haveWarned, const FormatOrString & fs); void warnOnce(bool & haveWarned, const FormatOrString & fs);
void writeToStderr(const string & s); void writeToStderr(std::string_view s);
} }

View file

@ -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<size_t>(source); auto len = readNum<size_t>(source);
if (len > max) throw SerialisationError("string is too long"); if (len > max) throw SerialisationError("string is too long");
@ -401,7 +401,7 @@ string readString(Source & source, size_t max)
return res; return res;
} }
Source & operator >> (Source & in, string & s) Source & operator >> (Source & in, std::string & s)
{ {
s = readString(in); s = readString(in);
return in; return in;

View file

@ -364,10 +364,10 @@ inline uint64_t readLongLong(Source & source)
void readPadding(size_t len, Source & source); void readPadding(size_t len, Source & source);
size_t readString(char * buf, size_t max, Source & source); size_t readString(char * buf, size_t max, Source & source);
string readString(Source & source, size_t max = std::numeric_limits<size_t>::max()); std::string readString(Source & source, size_t max = std::numeric_limits<size_t>::max());
template<class T> T readStrings(Source & source); template<class T> T readStrings(Source & source);
Source & operator >> (Source & in, string & s); Source & operator >> (Source & in, std::string & s);
template<typename T> template<typename T>
Source & operator >> (Source & in, T & n) Source & operator >> (Source & in, T & n)

View file

@ -5,9 +5,9 @@ namespace nix {
/* ----------- tests for url.hh --------------------------------------------------*/ /* ----------- tests for url.hh --------------------------------------------------*/
string print_map(std::map<string, string> m) { std::string print_map(std::map<std::string, std::string> m) {
std::map<string, string>::iterator it; std::map<std::string, std::string>::iterator it;
string s = "{ "; std::string s = "{ ";
for (it = m.begin(); it != m.end(); ++it) { for (it = m.begin(); it != m.end(); ++it) {
s += "{ "; s += "{ ";
s += it->first; s += it->first;
@ -262,21 +262,21 @@ namespace nix {
* --------------------------------------------------------------------------*/ * --------------------------------------------------------------------------*/
TEST(percentDecode, decodesUrlEncodedString) { TEST(percentDecode, decodesUrlEncodedString) {
string s = "==@=="; std::string s = "==@==";
string d = percentDecode("%3D%3D%40%3D%3D"); std::string d = percentDecode("%3D%3D%40%3D%3D");
ASSERT_EQ(d, s); ASSERT_EQ(d, s);
} }
TEST(percentDecode, multipleDecodesAreIdempotent) { TEST(percentDecode, multipleDecodesAreIdempotent) {
string once = percentDecode("%3D%3D%40%3D%3D"); std::string once = percentDecode("%3D%3D%40%3D%3D");
string twice = percentDecode(once); std::string twice = percentDecode(once);
ASSERT_EQ(once, twice); ASSERT_EQ(once, twice);
} }
TEST(percentDecode, trailingPercent) { TEST(percentDecode, trailingPercent) {
string s = "==@==%"; std::string s = "==@==%";
string d = percentDecode("%3D%3D%40%3D%3D%25"); std::string d = percentDecode("%3D%3D%40%3D%3D%25");
ASSERT_EQ(d, s); ASSERT_EQ(d, s);
} }

View file

@ -14,6 +14,7 @@ namespace nix {
typedef std::list<std::string> Strings; typedef std::list<std::string> Strings;
typedef std::set<std::string> StringSet; typedef std::set<std::string> StringSet;
typedef std::map<std::string, std::string> StringMap; typedef std::map<std::string, std::string> StringMap;
typedef std::map<std::string, std::string> StringPairs;
/* Paths are just strings. */ /* Paths are just strings. */
typedef std::string Path; typedef std::string Path;

View file

@ -110,13 +110,13 @@ Path canonPath(PathView path, bool resolveSymlinks)
{ {
assert(path != ""); assert(path != "");
string s; std::string s;
s.reserve(256); s.reserve(256);
if (path[0] != '/') if (path[0] != '/')
throw Error("not an absolute path: '%1%'", path); 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 /* Count the number of times we follow a symlink and stop at some
arbitrary (but high) limit to prevent infinite loops. */ arbitrary (but high) limit to prevent infinite loops. */
@ -142,7 +142,7 @@ Path canonPath(PathView path, bool resolveSymlinks)
/* Normal component; copy it. */ /* Normal component; copy it. */
else { else {
s += '/'; s += '/';
if (const auto slash = path.find('/'); slash == string::npos) { if (const auto slash = path.find('/'); slash == std::string::npos) {
s += path; s += path;
path = {}; path = {};
} else { } else {
@ -175,7 +175,7 @@ Path canonPath(PathView path, bool resolveSymlinks)
Path dirOf(const PathView path) Path dirOf(const PathView path)
{ {
Path::size_type pos = path.rfind('/'); Path::size_type pos = path.rfind('/');
if (pos == string::npos) if (pos == std::string::npos)
return "."; return ".";
return pos == 0 ? "/" : Path(path, 0, pos); return pos == 0 ? "/" : Path(path, 0, pos);
} }
@ -191,7 +191,7 @@ std::string_view baseNameOf(std::string_view path)
last -= 1; last -= 1;
auto pos = path.rfind('/', last); auto pos = path.rfind('/', last);
if (pos == string::npos) if (pos == std::string::npos)
pos = 0; pos = 0;
else else
pos += 1; pos += 1;
@ -249,7 +249,7 @@ Path readLink(const Path & path)
else else
throw SysError("reading symbolic link '%1%'", path); throw SysError("reading symbolic link '%1%'", path);
else if (rlSize < bufSize) 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; struct dirent * dirent;
while (errno = 0, dirent = readdir(dir)) { /* sic */ while (errno = 0, dirent = readdir(dir)) { /* sic */
checkInterrupt(); checkInterrupt();
string name = dirent->d_name; std::string name = dirent->d_name;
if (name == "." || name == "..") continue; if (name == "." || name == "..") continue;
entries.emplace_back(name, dirent->d_ino, entries.emplace_back(name, dirent->d_ino,
#ifdef HAVE_STRUCT_DIRENT_D_TYPE #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; struct stat st;
if (fstat(fd, &st) == -1) 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); AutoCloseFD fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
if (!fd) 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) { while (1) {
checkInterrupt(); checkInterrupt();
char ch; 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'; s += '\n';
writeFull(fd, s); writeFull(fd, s);
@ -398,7 +398,7 @@ static void _deletePath(int parentfd, const Path & path, uint64_t & bytesFreed)
{ {
checkInterrupt(); checkInterrupt();
string name(baseNameOf(path)); std::string name(baseNameOf(path));
struct stat st; struct stat st;
if (fstatat(parentfd, name.c_str(), &st, AT_SYMLINK_NOFOLLOW) == -1) { if (fstatat(parentfd, name.c_str(), &st, AT_SYMLINK_NOFOLLOW) == -1) {
@ -566,8 +566,8 @@ Path getConfigDir()
std::vector<Path> getConfigDirs() std::vector<Path> getConfigDirs()
{ {
Path configHome = getConfigDir(); Path configHome = getConfigDir();
string configDirs = getEnv("XDG_CONFIG_DIRS").value_or("/etc/xdg"); auto configDirs = getEnv("XDG_CONFIG_DIRS").value_or("/etc/xdg");
std::vector<Path> result = tokenizeString<std::vector<string>>(configDirs, ":"); std::vector<Path> result = tokenizeString<std::vector<std::string>>(configDirs, ":");
result.insert(result.begin(), configHome); result.insert(result.begin(), configHome);
return result; 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 // the parser needs two extra bytes to append terminating characters, other users will
// not care very much about the extra memory. // 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() : del{false} {}
AutoDelete::AutoDelete(const string & p, bool recursive) : path(p) AutoDelete::AutoDelete(const std::string & p, bool recursive) : path(p)
{ {
del = true; del = true;
this->recursive = recursive; this->recursive = recursive;
@ -1036,7 +1036,7 @@ std::vector<char *> stringsToCharPtrs(const Strings & ss)
return res; return res;
} }
string runProgram(Path program, bool searchPath, const Strings & args, std::string runProgram(Path program, bool searchPath, const Strings & args,
const std::optional<std::string> & input) const std::optional<std::string> & input)
{ {
auto res = runProgram(RunOptions {.program = program, .searchPath = searchPath, .args = args, .input = input}); auto res = runProgram(RunOptions {.program = program, .searchPath = searchPath, .args = args, .input = input});
@ -1238,11 +1238,11 @@ void _interrupted()
template<class C> C tokenizeString(std::string_view s, std::string_view separators) template<class C> C tokenizeString(std::string_view s, std::string_view separators)
{ {
C result; C result;
string::size_type pos = s.find_first_not_of(separators, 0); auto pos = s.find_first_not_of(separators, 0);
while (pos != string::npos) { while (pos != std::string::npos) {
string::size_type end = s.find_first_of(separators, pos + 1); auto end = s.find_first_of(separators, pos + 1);
if (end == string::npos) end = s.size(); if (end == std::string::npos) end = s.size();
result.insert(result.end(), string(s, pos, end - pos)); result.insert(result.end(), std::string(s, pos, end - pos));
pos = s.find_first_not_of(separators, end); pos = s.find_first_not_of(separators, end);
} }
return result; return result;
@ -1250,29 +1250,30 @@ template<class C> C tokenizeString(std::string_view s, std::string_view separato
template Strings tokenizeString(std::string_view s, std::string_view separators); template Strings tokenizeString(std::string_view s, std::string_view separators);
template StringSet tokenizeString(std::string_view s, std::string_view separators); template StringSet tokenizeString(std::string_view s, std::string_view separators);
template std::vector<string> tokenizeString(std::string_view s, std::string_view separators); template std::vector<std::string> 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"); 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); 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); 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, std::string replaceStrings(
const std::string & from, const std::string & to) std::string res,
std::string_view from,
std::string_view to)
{ {
string res(s);
if (from.empty()) return res; if (from.empty()) return res;
size_t pos = 0; size_t pos = 0;
while ((pos = res.find(from, pos)) != std::string::npos) { 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) { for (auto & i : rewrites) {
if (i.first == i.second) continue; if (i.first == i.second) continue;
size_t j = 0; 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); s.replace(j, i.first.size(), i.second);
} }
return s; return s;
} }
string statusToString(int status) std::string statusToString(int status)
{ {
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
if (WIFEXITED(status)) if (WIFEXITED(status))
@ -1448,9 +1448,9 @@ std::string filterANSIEscapes(const std::string & s, bool filterAll, unsigned in
constexpr char base64Chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; 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; int data = 0, nbits = 0;
for (char c : s) { 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 char npos = -1;
constexpr std::array<char, 256> base64DecodeChars = [&]() { constexpr std::array<char, 256> base64DecodeChars = [&]() {
@ -1481,7 +1481,7 @@ string base64Decode(std::string_view s)
return result; return result;
}(); }();
string res; std::string res;
unsigned int d = 0, bits = 0; unsigned int d = 0, bits = 0;
for (char c : s) { 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)); return fmt("%.2f MiB", bytes / (1024.0 * 1024.0));
} }
@ -1846,7 +1846,7 @@ void commonChildInit(Pipe & logPipe)
{ {
logger = makeSimpleLogger(); logger = makeSimpleLogger();
const static string pathNullDevice = "/dev/null"; const static std::string pathNullDevice = "/dev/null";
restoreProcessContext(false); restoreProcessContext(false);
/* Put the child in a separate session (and thus a separate /* Put the child in a separate session (and thus a separate

View file

@ -92,11 +92,11 @@ bool isLink(const Path & path);
removed. */ removed. */
struct DirEntry struct DirEntry
{ {
string name; std::string name;
ino_t ino; ino_t ino;
unsigned char type; // one of DT_* unsigned char type; // one of DT_*
DirEntry(const string & name, ino_t ino, unsigned char type) DirEntry(std::string name, ino_t ino, unsigned char type)
: name(name), ino(ino), type(type) { } : name(std::move(name)), ino(ino), type(type) { }
}; };
typedef std::vector<DirEntry> DirEntries; typedef std::vector<DirEntry> DirEntries;
@ -106,8 +106,8 @@ DirEntries readDirectory(const Path & path);
unsigned char getFileType(const Path & path); unsigned char getFileType(const Path & path);
/* Read the contents of a file into a string. */ /* Read the contents of a file into a string. */
string readFile(int fd); std::string readFile(int fd);
string readFile(const Path & path); std::string readFile(const Path & path);
void readFile(const Path & path, Sink & sink); void readFile(const Path & path, Sink & sink);
/* Write a string to a file. */ /* 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); void writeFile(const Path & path, Source & source, mode_t mode = 0666);
/* Read a line from a file descriptor. */ /* Read a line from a file descriptor. */
string readLine(int fd); std::string readLine(int fd);
/* Write a line to a file descriptor. */ /* 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 /* 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 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. */ /* 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); void drainFD(int fd, Sink & sink, bool block = true);
@ -268,7 +268,7 @@ void killUser(uid_t uid);
pid to the caller. */ pid to the caller. */
struct ProcessOptions struct ProcessOptions
{ {
string errorPrefix = ""; std::string errorPrefix = "";
bool dieWithParent = true; bool dieWithParent = true;
bool runExitHandlers = false; bool runExitHandlers = false;
bool allowVfork = false; bool allowVfork = false;
@ -279,7 +279,7 @@ pid_t startProcess(std::function<void()> fun, const ProcessOptions & options = P
/* Run a program and return its stdout in a string (i.e., like the /* Run a program and return its stdout in a string (i.e., like the
shell backtick operator). */ shell backtick operator). */
string runProgram(Path program, bool searchPath = false, std::string runProgram(Path program, bool searchPath = false,
const Strings & args = Strings(), const Strings & args = Strings(),
const std::optional<std::string> & input = {}); const std::optional<std::string> & input = {});
@ -378,12 +378,12 @@ template<class C> C tokenizeString(std::string_view s, std::string_view separato
/* Concatenate the given strings with a separator between the /* Concatenate the given strings with a separator between the
elements. */ elements. */
template<class C> template<class C>
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; size_t size = 0;
// need a cast to string_view since this is also called with Symbols // 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(); for (const auto & s : ss) size += sep.size() + std::string_view(s).size();
string s; std::string s;
s.reserve(size); s.reserve(size);
for (auto & i : ss) { for (auto & i : ss) {
if (s.size() != 0) s += sep; if (s.size() != 0) s += sep;
@ -394,7 +394,7 @@ string concatStringsSep(const std::string_view sep, const C & ss)
template<class ... Parts> template<class ... Parts>
auto concatStrings(Parts && ... parts) auto concatStrings(Parts && ... parts)
-> std::enable_if_t<(... && std::is_convertible_v<Parts, std::string_view>), string> -> std::enable_if_t<(... && std::is_convertible_v<Parts, std::string_view>), std::string>
{ {
std::string_view views[sizeof...(parts)] = { parts... }; std::string_view views[sizeof...(parts)] = { parts... };
return concatStringsSep({}, views); return concatStringsSep({}, views);
@ -413,24 +413,26 @@ template<class C> Strings quoteStrings(const C & c)
/* Remove trailing whitespace from a string. FIXME: return /* Remove trailing whitespace from a string. FIXME: return
std::string_view. */ 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. */ /* 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. */ /* Replace all occurrences of a string inside another string. */
string replaceStrings(std::string_view s, std::string replaceStrings(
const std::string & from, const std::string & to); 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 /* Convert the exit status of a child as returned by wait() into an
error string. */ error string. */
string statusToString(int status); std::string statusToString(int status);
bool statusOk(int status); bool statusOk(int status);
@ -525,8 +527,8 @@ std::string filterANSIEscapes(const std::string & s,
/* Base64 encoding/decoding. */ /* Base64 encoding/decoding. */
string base64Encode(std::string_view s); std::string base64Encode(std::string_view s);
string base64Decode(std::string_view s); std::string base64Decode(std::string_view s);
/* Remove common leading whitespace from the lines in the string /* Remove common leading whitespace from the lines in the string

View file

@ -32,11 +32,11 @@ extern char * * environ __attribute__((weak));
/* Recreate the effect of the perl shellwords function, breaking up a /* Recreate the effect of the perl shellwords function, breaking up a
* string into arguments like a shell word, including escapes * string into arguments like a shell word, including escapes
*/ */
std::vector<string> shellwords(const string & s) static std::vector<std::string> shellwords(const std::string & s)
{ {
std::regex whitespace("^(\\s+).*"); std::regex whitespace("^(\\s+).*");
auto begin = s.cbegin(); auto begin = s.cbegin();
std::vector<string> res; std::vector<std::string> res;
std::string cur; std::string cur;
enum state { enum state {
sBegin, sBegin,
@ -96,14 +96,14 @@ static void main_nix_build(int argc, char * * argv)
auto inShebang = false; auto inShebang = false;
std::string script; std::string script;
std::vector<string> savedArgs; std::vector<std::string> savedArgs;
AutoDelete tmpDir(createTempDir("", myName)); AutoDelete tmpDir(createTempDir("", myName));
std::string outLink = "./result"; std::string outLink = "./result";
// List of environment variables kept for --pure // List of environment variables kept for --pure
std::set<string> keepVars{ std::set<std::string> keepVars{
"HOME", "XDG_RUNTIME_DIR", "USER", "LOGNAME", "DISPLAY", "HOME", "XDG_RUNTIME_DIR", "USER", "LOGNAME", "DISPLAY",
"WAYLAND_DISPLAY", "WAYLAND_SOCKET", "PATH", "TERM", "IN_NIX_SHELL", "WAYLAND_DISPLAY", "WAYLAND_SOCKET", "PATH", "TERM", "IN_NIX_SHELL",
"NIX_SHELL_PRESERVE_PROMPT", "TZ", "PAGER", "NIX_BUILD_SHELL", "SHLVL", "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. // Build or fetch all dependencies of the derivation.
for (const auto & input : drv.inputDrvs) for (const auto & input : drv.inputDrvs)
if (std::all_of(envExclude.cbegin(), envExclude.cend(), 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}); pathsToBuild.push_back({input.first, input.second});
pathsToCopy.insert(input.first); pathsToCopy.insert(input.first);
@ -437,7 +439,7 @@ static void main_nix_build(int argc, char * * argv)
for (auto & var : drv.env) for (auto & var : drv.env)
if (passAsFile.count(var.first)) { if (passAsFile.count(var.first)) {
keepTmp = true; keepTmp = true;
string fn = ".attr-" + std::to_string(fileNr++); auto fn = ".attr-" + std::to_string(fileNr++);
Path p = (Path) tmpDir + "/" + fn; Path p = (Path) tmpDir + "/" + fn;
writeFile(p, var.second); writeFile(p, var.second);
env[var.first + "Path"] = p; env[var.first + "Path"] = p;
@ -514,7 +516,7 @@ static void main_nix_build(int argc, char * * argv)
(pure ? "" : "PATH=$PATH:$p; unset p; "), (pure ? "" : "PATH=$PATH:$p; unset p; "),
shellEscape(dirOf(*shell)), shellEscape(dirOf(*shell)),
shellEscape(*shell), shellEscape(*shell),
(getenv("TZ") ? (string("export TZ=") + shellEscape(getenv("TZ")) + "; ") : ""), (getenv("TZ") ? (std::string("export TZ=") + shellEscape(getenv("TZ")) + "; ") : ""),
envCommand); envCommand);
vomit("Sourcing nix-shell with file %s and contents:\n%s", rcfile, rc); vomit("Sourcing nix-shell with file %s and contents:\n%s", rcfile, rc);
writeFile(rcfile, rc); writeFile(rcfile, rc);

View file

@ -11,7 +11,7 @@
using namespace nix; using namespace nix;
typedef std::map<string,string> Channels; typedef std::map<std::string, std::string> Channels;
static Channels channels; static Channels channels;
static Path channelsList; static Path channelsList;
@ -22,11 +22,11 @@ static void readChannels()
if (!pathExists(channelsList)) return; if (!pathExists(channelsList)) return;
auto channelsFile = readFile(channelsList); auto channelsFile = readFile(channelsList);
for (const auto & line : tokenizeString<std::vector<string>>(channelsFile, "\n")) { for (const auto & line : tokenizeString<std::vector<std::string>>(channelsFile, "\n")) {
chomp(line); chomp(line);
if (std::regex_search(line, std::regex("^\\s*\\#"))) if (std::regex_search(line, std::regex("^\\s*\\#")))
continue; continue;
auto split = tokenizeString<std::vector<string>>(line, " "); auto split = tokenizeString<std::vector<std::string>>(line, " ");
auto url = std::regex_replace(split[0], std::regex("/*$"), ""); auto url = std::regex_replace(split[0], std::regex("/*$"), "");
auto name = split.size() > 1 ? split[1] : std::string(baseNameOf(url)); auto name = split.size() > 1 ? split[1] : std::string(baseNameOf(url));
channels[name] = url; channels[name] = url;
@ -44,7 +44,7 @@ static void writeChannels()
} }
// Adds a channel. // 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)://"))) if (!regex_search(url, std::regex("^(file|http|https)://")))
throw Error("invalid channel URL '%1%'", url); throw Error("invalid channel URL '%1%'", url);
@ -58,7 +58,7 @@ static void addChannel(const string & url, const string & name)
static Path profile; static Path profile;
// Remove a channel. // Remove a channel.
static void removeChannel(const string & name) static void removeChannel(const std::string & name)
{ {
readChannels(); readChannels();
channels.erase(name); channels.erase(name);
@ -96,7 +96,7 @@ static void update(const StringSet & channelNames)
std::smatch match; std::smatch match;
auto urlBase = std::string(baseNameOf(url)); auto urlBase = std::string(baseNameOf(url));
if (std::regex_search(urlBase, match, std::regex("(-\\d.*)$"))) if (std::regex_search(urlBase, match, std::regex("(-\\d.*)$")))
cname = cname + (string) match[1]; cname = cname + (std::string) match[1];
std::string extraAttrs; std::string extraAttrs;
@ -176,7 +176,7 @@ static int main_nix_channel(int argc, char ** argv)
cUpdate, cUpdate,
cRollback cRollback
} cmd = cNone; } cmd = cNone;
std::vector<string> args; std::vector<std::string> args;
parseCmdLine(argc, argv, [&](Strings::iterator & arg, const Strings::iterator & end) { parseCmdLine(argc, argv, [&](Strings::iterator & arg, const Strings::iterator & end) {
if (*arg == "--help") { if (*arg == "--help") {
showManPage("nix-channel"); showManPage("nix-channel");

View file

@ -36,7 +36,7 @@ void removeOldGenerations(std::string dir)
} catch (SysError & e) { } catch (SysError & e) {
if (e.errNo == ENOENT) continue; 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); printInfo(format("removing old generations of profile %1%") % path);
if (deleteOlderThan != "") if (deleteOlderThan != "")
deleteGenerationsOlderThan(path, deleteOlderThan, dryRun); deleteGenerationsOlderThan(path, deleteOlderThan, dryRun);

View file

@ -46,7 +46,7 @@ struct InstallSourceInfo
InstallSourceType type; InstallSourceType type;
Path nixExprPath; /* for srcNixExprDrvs, srcNixExprs */ Path nixExprPath; /* for srcNixExprDrvs, srcNixExprs */
Path profile; /* for srcProfile */ Path profile; /* for srcProfile */
string systemFilter; /* for srcNixExprDrvs */ std::string systemFilter; /* for srcNixExprDrvs */
Bindings * autoArgs; Bindings * autoArgs;
}; };
@ -59,7 +59,7 @@ struct Globals
bool dryRun; bool dryRun;
bool preserveInstalled; bool preserveInstalled;
bool removeAll; bool removeAll;
string forceName; std::string forceName;
bool prebuiltOnly; bool prebuiltOnly;
}; };
@ -68,8 +68,8 @@ typedef void (* Operation) (Globals & globals,
Strings opFlags, Strings opArgs); Strings opFlags, Strings opArgs);
static string needArg(Strings::iterator & i, static std::string needArg(Strings::iterator & i,
Strings & args, const string & arg) Strings & args, const std::string & arg)
{ {
if (i == args.end()) throw UsageError("'%1%' requires an argument", arg); if (i == args.end()) throw UsageError("'%1%' requires an argument", arg);
return *i++; return *i++;
@ -77,7 +77,7 @@ static string needArg(Strings::iterator & i,
static bool parseInstallSourceOptions(Globals & globals, 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") if (arg == "--from-expression" || arg == "-E")
globals.instSource.type = srcNixExprs; globals.instSource.type = srcNixExprs;
@ -124,9 +124,9 @@ static void getAllExprs(EvalState & state,
otherwise the attribute cannot be selected with the otherwise the attribute cannot be selected with the
`-A' option. Useful if you want to stick a Nix `-A' option. Useful if you want to stick a Nix
expression directly in ~/.nix-defexpr. */ expression directly in ~/.nix-defexpr. */
string attrName = i; std::string attrName = i;
if (hasSuffix(attrName, ".nix")) if (hasSuffix(attrName, ".nix"))
attrName = string(attrName, 0, attrName.size() - 4); attrName = std::string(attrName, 0, attrName.size() - 4);
if (!seen.insert(attrName).second) { if (!seen.insert(attrName).second) {
printError("warning: name collision in input Nix expressions, skipping '%1%'", path2); printError("warning: name collision in input Nix expressions, skipping '%1%'", path2);
continue; continue;
@ -175,8 +175,8 @@ static void loadSourceExpr(EvalState & state, const Path & path, Value & v)
static void loadDerivations(EvalState & state, Path nixExprPath, static void loadDerivations(EvalState & state, Path nixExprPath,
string systemFilter, Bindings & autoArgs, std::string systemFilter, Bindings & autoArgs,
const string & pathPrefix, DrvInfos & elems) const std::string & pathPrefix, DrvInfos & elems)
{ {
Value vRoot; Value vRoot;
loadSourceExpr(state, nixExprPath, vRoot); loadSourceExpr(state, nixExprPath, vRoot);
@ -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); auto outputs = state.store->queryDerivationOutputMap(path);
elem.setOutPath(state.store->printStorePath(outputs.at("out"))); elem.setOutPath(state.store->printStorePath(outputs.at("out")));
if (name.size() >= drvExtension.size() && if (name.size() >= drvExtension.size() &&
string(name, name.size() - drvExtension.size()) == drvExtension) std::string(name, name.size() - drvExtension.size()) == drvExtension)
name = string(name, 0, name.size() - drvExtension.size()); name = name.substr(0, name.size() - drvExtension.size());
} }
else elem.setOutPath(state.store->printStorePath(path)); else elem.setOutPath(state.store->printStorePath(path));
@ -515,7 +515,7 @@ static void installDerivations(Globals & globals,
while (true) { while (true) {
string lockToken = optimisticLockProfile(profile); auto lockToken = optimisticLockProfile(profile);
DrvInfos allElems(newElems); DrvInfos allElems(newElems);
@ -551,7 +551,7 @@ static void installDerivations(Globals & globals,
static void opInstall(Globals & globals, Strings opFlags, Strings opArgs) static void opInstall(Globals & globals, Strings opFlags, Strings opArgs)
{ {
for (Strings::iterator i = opFlags.begin(); i != opFlags.end(); ) { for (Strings::iterator i = opFlags.begin(); i != opFlags.end(); ) {
string arg = *i++; auto arg = *i++;
if (parseInstallSourceOptions(globals, i, opFlags, arg)) ; if (parseInstallSourceOptions(globals, i, opFlags, arg)) ;
else if (arg == "--preserve-installed" || arg == "-P") else if (arg == "--preserve-installed" || arg == "-P")
globals.preserveInstalled = true; globals.preserveInstalled = true;
@ -578,7 +578,7 @@ static void upgradeDerivations(Globals & globals,
name and a higher version number. */ name and a higher version number. */
while (true) { while (true) {
string lockToken = optimisticLockProfile(globals.profile); auto lockToken = optimisticLockProfile(globals.profile);
DrvInfos installedElems = queryInstalled(*globals.state, 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. take the one with the highest version.
Do not upgrade if it would decrease the priority. */ Do not upgrade if it would decrease the priority. */
DrvInfos::iterator bestElem = availElems.end(); DrvInfos::iterator bestElem = availElems.end();
string bestVersion; std::string bestVersion;
for (auto j = availElems.begin(); j != availElems.end(); ++j) { for (auto j = availElems.begin(); j != availElems.end(); ++j) {
if (comparePriorities(*globals.state, i, *j) > 0) if (comparePriorities(*globals.state, i, *j) > 0)
continue; continue;
@ -662,7 +662,7 @@ static void opUpgrade(Globals & globals, Strings opFlags, Strings opArgs)
{ {
UpgradeType upgradeType = utLt; UpgradeType upgradeType = utLt;
for (Strings::iterator i = opFlags.begin(); i != opFlags.end(); ) { for (Strings::iterator i = opFlags.begin(); i != opFlags.end(); ) {
string arg = *i++; std::string arg = *i++;
if (parseInstallSourceOptions(globals, i, opFlags, arg)) ; if (parseInstallSourceOptions(globals, i, opFlags, arg)) ;
else if (arg == "--lt") upgradeType = utLt; else if (arg == "--lt") upgradeType = utLt;
else if (arg == "--leq") upgradeType = utLeq; 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, 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(); auto v = state.allocValue();
v->mkString(value); v->mkString(value);
@ -692,12 +692,12 @@ static void opSetFlag(Globals & globals, Strings opFlags, Strings opArgs)
throw UsageError("not enough arguments to '--set-flag'"); throw UsageError("not enough arguments to '--set-flag'");
Strings::iterator arg = opArgs.begin(); Strings::iterator arg = opArgs.begin();
string flagName = *arg++; std::string flagName = *arg++;
string flagValue = *arg++; std::string flagValue = *arg++;
DrvNames selectors = drvNamesFromArgs(Strings(arg, opArgs.end())); DrvNames selectors = drvNamesFromArgs(Strings(arg, opArgs.end()));
while (true) { while (true) {
string lockToken = optimisticLockProfile(globals.profile); std::string lockToken = optimisticLockProfile(globals.profile);
DrvInfos installedElems = queryInstalled(*globals.state, 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"); if (!store2) throw Error("--set is not supported for this Nix store");
for (Strings::iterator i = opFlags.begin(); i != opFlags.end(); ) { for (Strings::iterator i = opFlags.begin(); i != opFlags.end(); ) {
string arg = *i++; std::string arg = *i++;
if (parseInstallSourceOptions(globals, i, opFlags, arg)) ; if (parseInstallSourceOptions(globals, i, opFlags, arg)) ;
else throw UsageError("unknown flag '%1%'", arg); else throw UsageError("unknown flag '%1%'", arg);
} }
@ -769,7 +769,7 @@ static void uninstallDerivations(Globals & globals, Strings & selectors,
Path & profile) Path & profile)
{ {
while (true) { while (true) {
string lockToken = optimisticLockProfile(profile); auto lockToken = optimisticLockProfile(profile);
DrvInfos workingElems = queryInstalled(*globals.state, profile); DrvInfos workingElems = queryInstalled(*globals.state, profile);
@ -855,11 +855,11 @@ void printTable(Table & table)
Strings::iterator j; Strings::iterator j;
size_t column; size_t column;
for (j = i.begin(), column = 0; j != i.end(); ++j, ++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', ' '); replace(s.begin(), s.end(), '\n', ' ');
cout << s; cout << s;
if (column < nrColumns - 1) if (column < nrColumns - 1)
cout << string(widths[column] - s.size() + 2, ' '); cout << std::string(widths[column] - s.size() + 2, ' ');
} }
cout << std::endl; cout << std::endl;
} }
@ -876,7 +876,7 @@ void printTable(Table & table)
typedef enum { cvLess, cvEqual, cvGreater, cvUnavail } VersionDiff; typedef enum { cvLess, cvEqual, cvGreater, cvUnavail } VersionDiff;
static VersionDiff compareVersionAgainstSet( static VersionDiff compareVersionAgainstSet(
const DrvInfo & elem, const DrvInfos & elems, string & version) const DrvInfo & elem, const DrvInfos & elems, std::string & version)
{ {
DrvName name(elem.queryName()); DrvName name(elem.queryName());
@ -958,7 +958,7 @@ static void queryJSON(Globals & globals, std::vector<DrvInfo> & elems, bool prin
static void opQuery(Globals & globals, Strings opFlags, Strings opArgs) static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
{ {
Strings remaining; Strings remaining;
string attrPath; std::string attrPath;
bool printStatus = false; bool printStatus = false;
bool printName = true; bool printName = true;
@ -977,7 +977,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
settings.readOnlyMode = true; /* makes evaluation a bit faster */ settings.readOnlyMode = true; /* makes evaluation a bit faster */
for (Strings::iterator i = opFlags.begin(); i != opFlags.end(); ) { for (Strings::iterator i = opFlags.begin(); i != opFlags.end(); ) {
string arg = *i++; auto arg = *i++;
if (arg == "--status" || arg == "-s") printStatus = true; if (arg == "--status" || arg == "-s") printStatus = true;
else if (arg == "--no-name") printName = false; else if (arg == "--no-name") printName = false;
else if (arg == "--system") printSystem = true; else if (arg == "--system") printSystem = true;
@ -1094,7 +1094,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
attrs["substitutable"] = hasSubs ? "1" : "0"; attrs["substitutable"] = hasSubs ? "1" : "0";
} else } else
columns.push_back( columns.push_back(
(string) (isInstalled ? "I" : "-") (std::string) (isInstalled ? "I" : "-")
+ (isValid ? "P" : "-") + (isValid ? "P" : "-")
+ (hasSubs ? "S" : "-")); + (hasSubs ? "S" : "-"));
} }
@ -1118,7 +1118,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
same named packages in either the set of available same named packages in either the set of available
elements, or the set of installed elements. !!! elements, or the set of installed elements. !!!
This is O(N * M), should be O(N * lg M). */ This is O(N * M), should be O(N * lg M). */
string version; std::string version;
VersionDiff diff = compareVersionAgainstSet(i, otherElems, version); VersionDiff diff = compareVersionAgainstSet(i, otherElems, version);
char ch; char ch;
@ -1136,7 +1136,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
attrs["maxComparedVersion"] = version; attrs["maxComparedVersion"] = version;
} }
} else { } else {
string column = (string) "" + ch + " " + version; auto column = (std::string) "" + ch + " " + version;
if (diff == cvGreater && tty) if (diff == cvGreater && tty)
column = ANSI_RED + column + ANSI_NORMAL; column = ANSI_RED + column + ANSI_NORMAL;
columns.push_back(column); columns.push_back(column);
@ -1150,7 +1150,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
columns.push_back(i.querySystem()); columns.push_back(i.querySystem());
if (printDrvPath) { if (printDrvPath) {
string drvPath = i.queryDrvPath(); auto drvPath = i.queryDrvPath();
if (xmlOutput) { if (xmlOutput) {
if (drvPath != "") attrs["drvPath"] = drvPath; if (drvPath != "") attrs["drvPath"] = drvPath;
} else } else
@ -1159,7 +1159,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
if (printOutPath && !xmlOutput) { if (printOutPath && !xmlOutput) {
DrvInfo::Outputs outputs = i.queryOutputs(); DrvInfo::Outputs outputs = i.queryOutputs();
string s; std::string s;
for (auto & j : outputs) { for (auto & j : outputs) {
if (!s.empty()) s += ';'; if (!s.empty()) s += ';';
if (j.first != "out") { s += j.first; s += "="; } if (j.first != "out") { s += j.first; s += "="; }
@ -1169,7 +1169,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
} }
if (printDescription) { if (printDescription) {
string descr = i.queryMetaString("description"); auto descr = i.queryMetaString("description");
if (xmlOutput) { if (xmlOutput) {
if (descr != "") attrs["description"] = descr; if (descr != "") attrs["description"] = descr;
} else } else
@ -1331,12 +1331,12 @@ static void opDeleteGenerations(Globals & globals, Strings opFlags, Strings opAr
if (opArgs.size() == 1 && opArgs.front() == "old") { if (opArgs.size() == 1 && opArgs.front() == "old") {
deleteOldGenerations(globals.profile, globals.dryRun); 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); 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) if (opArgs.front().size() < 2)
throw Error("invalid number of generations '%1%'", opArgs.front()); 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<GenerationNumber>(str_max); auto max = string2Int<GenerationNumber>(str_max);
if (!max || *max == 0) if (!max || *max == 0)
throw Error("invalid number of generations to keep '%1%'", opArgs.front()); 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; Strings opFlags, opArgs;
Operation op = 0; Operation op = 0;
RepairFlag repair = NoRepair; RepairFlag repair = NoRepair;
string file; std::string file;
Globals globals; Globals globals;

View file

@ -32,7 +32,7 @@ DrvInfos queryInstalled(EvalState & state, const Path & userEnv)
bool createUserEnv(EvalState & state, DrvInfos & elems, bool createUserEnv(EvalState & state, DrvInfos & elems,
const Path & profile, bool keepDerivations, const Path & profile, bool keepDerivations,
const string & lockToken) const std::string & lockToken)
{ {
/* Build the components in the user environment, if they don't /* Build the components in the user environment, if they don't
exist already. */ exist already. */

Some files were not shown because too many files have changed in this diff Show more