style(3p/nix): Enforce braces around loops and conditionals

This change was generated with:

  fd -e cc -e hh | xargs -I{} clang-tidy {} -p ~/projects/nix-build/ \
    --checks='-*,readability-braces-around-statements' --fix \
    -fix-errors

Some manual fixes were applied because some convoluted unbraced
statements couldn't be untangled by clang-tidy.

This commit still includes invalid files, but I decided to clean them
up in a subsequent commit so that it becomes more obvious where
clang-tidy failed. Maybe this will allow for a bug-report to
clang-tidy.
This commit is contained in:
Vincent Ambo 2020-05-19 17:38:04 +01:00
parent c758de9d22
commit b490742a51
44 changed files with 661 additions and 298 deletions

View file

@ -38,33 +38,39 @@ void EvalState::forceValue(Value& v, const Pos& pos) {
v.thunk.expr = expr; v.thunk.expr = expr;
throw; throw;
} }
} else if (v.type == tApp) } else if (v.type == tApp) {
callFunction(*v.app.left, *v.app.right, v, noPos); callFunction(*v.app.left, *v.app.right, v, noPos);
else if (v.type == tBlackhole) } else if (v.type == tBlackhole) {
throwEvalError("infinite recursion encountered, at %1%", pos); throwEvalError("infinite recursion encountered, at %1%", pos);
}
} }
inline void EvalState::forceAttrs(Value& v) { inline void EvalState::forceAttrs(Value& v) {
forceValue(v); forceValue(v);
if (v.type != tAttrs) if (v.type != tAttrs) {
throwTypeError("value is %1% while a set was expected", v); throwTypeError("value is %1% while a set was expected", v);
}
} }
inline void EvalState::forceAttrs(Value& v, const Pos& pos) { inline void EvalState::forceAttrs(Value& v, const Pos& pos) {
forceValue(v); forceValue(v);
if (v.type != tAttrs) if (v.type != tAttrs) {
throwTypeError("value is %1% while a set was expected, at %2%", v, pos); throwTypeError("value is %1% while a set was expected, at %2%", v, pos);
}
} }
inline void EvalState::forceList(Value& v) { inline void EvalState::forceList(Value& v) {
forceValue(v); forceValue(v);
if (!v.isList()) throwTypeError("value is %1% while a list was expected", v); if (!v.isList()) {
throwTypeError("value is %1% while a list was expected", v);
}
} }
inline void EvalState::forceList(Value& v, const Pos& pos) { inline void EvalState::forceList(Value& v, const Pos& pos) {
forceValue(v); forceValue(v);
if (!v.isList()) if (!v.isList()) {
throwTypeError("value is %1% while a list was expected, at %2%", v, pos); throwTypeError("value is %1% while a list was expected, at %2%", v, pos);
}
} }
/* Note: Various places expect the allocated memory to be zeroed. */ /* Note: Various places expect the allocated memory to be zeroed. */

View file

@ -545,14 +545,19 @@ Value& mkString(Value& v, const string& s, const PathSet& context) {
void mkPath(Value& v, const char* s) { mkPathNoCopy(v, dupString(s)); } void mkPath(Value& v, const char* s) { mkPathNoCopy(v, dupString(s)); }
inline Value* EvalState::lookupVar(Env* env, const ExprVar& var, bool noEval) { inline Value* EvalState::lookupVar(Env* env, const ExprVar& var, bool noEval) {
for (size_t l = var.level; l; --l, env = env->up) for (size_t l = var.level; l; --l, env = env->up) {
; ;
}
if (!var.fromWith) return env->values[var.displ]; if (!var.fromWith) {
return env->values[var.displ];
}
while (1) { while (1) {
if (env->type == Env::HasWithExpr) { if (env->type == Env::HasWithExpr) {
if (noEval) return 0; if (noEval) {
return 0;
}
Value* v = allocValue(); Value* v = allocValue();
evalAttrs(*env->up, (Expr*)env->values[0], *v); evalAttrs(*env->up, (Expr*)env->values[0], *v);
env->values[0] = v; env->values[0] = v;
@ -566,9 +571,10 @@ inline Value* EvalState::lookupVar(Env* env, const ExprVar& var, bool noEval) {
if (!env->prevWith) if (!env->prevWith)
throwUndefinedVarError("undefined variable '%1%' at %2%", var.name, throwUndefinedVarError("undefined variable '%1%' at %2%", var.name,
var.pos); var.pos);
for (size_t l = env->prevWith; l; --l, env = env->up) for (size_t l = env->prevWith; l; --l, env = env->up) {
; ;
} }
}
} }
std::atomic<uint64_t> nrValuesFreed{0}; std::atomic<uint64_t> nrValuesFreed{0};
@ -601,11 +607,11 @@ Env& EvalState::allocEnv(size_t size) {
void EvalState::mkList(Value& v, size_t size) { void EvalState::mkList(Value& v, size_t size) {
clearValue(v); clearValue(v);
if (size == 1) if (size == 1) {
v.type = tList1; v.type = tList1;
else if (size == 2) } else if (size == 2) {
v.type = tList2; v.type = tList2;
else { } else {
v.type = tListN; v.type = tListN;
v.bigList.size = size; v.bigList.size = size;
v.bigList.elems = size ? (Value**)allocBytes(size * sizeof(Value*)) : 0; v.bigList.elems = size ? (Value**)allocBytes(size * sizeof(Value*)) : 0;
@ -699,7 +705,9 @@ void EvalState::evalFile(const Path& path_, Value& v) {
auto j = fileParseCache.find(path2); auto j = fileParseCache.find(path2);
if (j != fileParseCache.end()) e = j->second; if (j != fileParseCache.end()) e = j->second;
if (!e) e = parseExprFromFile(checkSourcePath(path2)); if (!e) {
e = parseExprFromFile(checkSourcePath(path2));
}
fileParseCache[path2] = e; fileParseCache[path2] = e;
@ -724,23 +732,26 @@ void EvalState::eval(Expr* e, Value& v) { e->eval(*this, baseEnv, v); }
inline bool EvalState::evalBool(Env& env, Expr* e) { inline bool EvalState::evalBool(Env& env, Expr* e) {
Value v; Value v;
e->eval(*this, env, v); e->eval(*this, env, v);
if (v.type != tBool) if (v.type != tBool) {
throwTypeError("value is %1% while a Boolean was expected", v); throwTypeError("value is %1% while a Boolean was expected", v);
}
return v.boolean; return v.boolean;
} }
inline bool EvalState::evalBool(Env& env, Expr* e, const Pos& pos) { inline bool EvalState::evalBool(Env& env, Expr* e, const Pos& pos) {
Value v; Value v;
e->eval(*this, env, v); e->eval(*this, env, v);
if (v.type != tBool) if (v.type != tBool) {
throwTypeError("value is %1% while a Boolean was expected, at %2%", v, pos); throwTypeError("value is %1% while a Boolean was expected, at %2%", v, pos);
}
return v.boolean; return v.boolean;
} }
inline void EvalState::evalAttrs(Env& env, Expr* e, Value& v) { inline void EvalState::evalAttrs(Env& env, Expr* e, Value& v) {
e->eval(*this, env, v); e->eval(*this, env, v);
if (v.type != tAttrs) if (v.type != tAttrs) {
throwTypeError("value is %1% while a set was expected", v); throwTypeError("value is %1% while a set was expected", v);
}
} }
void Expr::eval(EvalState& state, Env& env, Value& v) { abort(); } void Expr::eval(EvalState& state, Env& env, Value& v) { abort(); }
@ -795,7 +806,9 @@ void ExprAttrs::eval(EvalState& state, Env& env, Value& v) {
state.forceAttrs(*vOverrides); state.forceAttrs(*vOverrides);
Bindings* newBnds = Bindings* newBnds =
state.allocBindings(v.attrs->capacity() + vOverrides->attrs->size()); state.allocBindings(v.attrs->capacity() + vOverrides->attrs->size());
for (auto& i : *v.attrs) newBnds->push_back(i); for (auto& i : *v.attrs) {
newBnds->push_back(i);
}
for (auto& i : *vOverrides->attrs) { for (auto& i : *vOverrides->attrs) {
AttrDefs::iterator j = attrs.find(i.name); AttrDefs::iterator j = attrs.find(i.name);
if (j != attrs.end()) { if (j != attrs.end()) {
@ -809,10 +822,12 @@ void ExprAttrs::eval(EvalState& state, Env& env, Value& v) {
} }
} }
else else {
for (auto& i : attrs) for
v.attrs->push_back( }
Attr(i.first, i.second.e->maybeThunk(state, env), &i.second.pos)); (auto& i
: attrs) v.attrs->push_back(Attr(i.first, i.second.e->maybeThunk(state, env),
&i.second.pos));
/* Dynamic attrs apply *after* rec and __overrides. */ /* Dynamic attrs apply *after* rec and __overrides. */
for (auto& i : dynamicAttrs) { for (auto& i : dynamicAttrs) {
@ -980,8 +995,10 @@ void EvalState::callPrimOp(Value& fun, Value& arg, Value& v, const Pos& pos) {
Value* vArgs[arity]; Value* vArgs[arity];
auto n = arity - 1; auto n = arity - 1;
vArgs[n--] = &arg; vArgs[n--] = &arg;
for (Value* arg = &fun; arg->type == tPrimOpApp; arg = arg->primOpApp.left) for (Value* arg = &fun; arg->type == tPrimOpApp;
arg = arg->primOpApp.left) {
vArgs[n--] = arg->primOpApp.right; vArgs[n--] = arg->primOpApp.right;
}
/* And call the primop. */ /* And call the primop. */
nrPrimOpCalls++; nrPrimOpCalls++;
@ -1024,10 +1041,11 @@ void EvalState::callFunction(Value& fun, Value& arg, Value& v, const Pos& pos) {
} }
} }
if (fun.type != tLambda) if (fun.type != tLambda) {
throwTypeError( throwTypeError(
"attempt to call something which is not a function but %1%, at %2%", "attempt to call something which is not a function but %1%, at %2%",
fun, pos); fun, pos);
}
ExprLambda& lambda(*fun.lambda.fun); ExprLambda& lambda(*fun.lambda.fun);
@ -1038,10 +1056,10 @@ void EvalState::callFunction(Value& fun, Value& arg, Value& v, const Pos& pos) {
size_t displ = 0; size_t displ = 0;
if (!lambda.matchAttrs) if (!lambda.matchAttrs) {
env2.values[displ++] = &arg; env2.values[displ++] = &arg;
else { } else {
forceAttrs(arg, pos); forceAttrs(arg, pos);
if (!lambda.arg.empty()) env2.values[displ++] = &arg; if (!lambda.arg.empty()) env2.values[displ++] = &arg;
@ -1078,7 +1096,9 @@ void EvalState::callFunction(Value& fun, Value& arg, Value& v, const Pos& pos) {
} }
nrFunctionCalls++; nrFunctionCalls++;
if (countCalls) incrFunctionCall(&lambda); if (countCalls) {
incrFunctionCall(&lambda);
}
/* Evaluate the body. This is conditional on showTrace, because /* Evaluate the body. This is conditional on showTrace, because
catching exceptions makes this function not tail-recursive. */ catching exceptions makes this function not tail-recursive. */
@ -1223,8 +1243,12 @@ void ExprOpUpdate::eval(EvalState& state, Env& env, Value& v) {
v.attrs->push_back(*j++); v.attrs->push_back(*j++);
} }
while (i != v1.attrs->end()) v.attrs->push_back(*i++); while (i != v1.attrs->end()) {
while (j != v2.attrs->end()) v.attrs->push_back(*j++); v.attrs->push_back(*i++);
}
while (j != v2.attrs->end()) {
v.attrs->push_back(*j++);
}
state.nrOpUpdateValuesCopied += v.attrs->size(); state.nrOpUpdateValuesCopied += v.attrs->size();
} }
@ -1248,7 +1272,9 @@ void EvalState::concatLists(Value& v, size_t nrLists, Value** lists,
forceList(*lists[n], pos); forceList(*lists[n], pos);
auto l = lists[n]->listSize(); auto l = lists[n]->listSize();
len += l; len += l;
if (l) nonEmpty = lists[n]; if (l) {
nonEmpty = lists[n];
}
} }
if (nonEmpty && len == nonEmpty->listSize()) { if (nonEmpty && len == nonEmpty->listSize()) {
@ -1311,11 +1337,11 @@ void ExprConcatStrings::eval(EvalState& state, Env& env, Value& v) {
firstType == tString); firstType == tString);
} }
if (firstType == tInt) if (firstType == tInt) {
mkInt(v, n); mkInt(v, n);
else if (firstType == tFloat) } else if (firstType == tFloat) {
mkFloat(v, nf); mkFloat(v, nf);
else if (firstType == tPath) { } else if (firstType == tPath) {
if (!context.empty()) if (!context.empty())
throwEvalError( throwEvalError(
"a string that refers to a store path cannot be appended to a path, " "a string that refers to a store path cannot be appended to a path, "
@ -1323,8 +1349,10 @@ void ExprConcatStrings::eval(EvalState& state, Env& env, Value& v) {
pos); pos);
auto path = canonPath(s.str()); auto path = canonPath(s.str());
mkPath(v, path.c_str()); mkPath(v, path.c_str());
} else } else {
mkString(v, s.str(), context); mkString
}
(v, s.str(), context);
} }
void ExprPos::eval(EvalState& state, Env& env, Value& v) { void ExprPos::eval(EvalState& state, Env& env, Value& v) {
@ -1362,25 +1390,28 @@ void EvalState::forceValueDeep(Value& v) {
NixInt EvalState::forceInt(Value& v, const Pos& pos) { NixInt EvalState::forceInt(Value& v, const Pos& pos) {
forceValue(v, pos); forceValue(v, pos);
if (v.type != tInt) if (v.type != tInt) {
throwTypeError("value is %1% while an integer was expected, at %2%", v, throwTypeError("value is %1% while an integer was expected, at %2%", v,
pos); pos);
}
return v.integer; return v.integer;
} }
NixFloat EvalState::forceFloat(Value& v, const Pos& pos) { NixFloat EvalState::forceFloat(Value& v, const Pos& pos) {
forceValue(v, pos); forceValue(v, pos);
if (v.type == tInt) if (v.type == tInt) {
return v.integer; return v.integer;
else if (v.type != tFloat) } else if (v.type != tFloat) {
throwTypeError("value is %1% while a float was expected, at %2%", v, pos); throwTypeError("value is %1% while a float was expected, at %2%", v, pos);
}
return v.fpoint; return v.fpoint;
} }
bool EvalState::forceBool(Value& v, const Pos& pos) { bool EvalState::forceBool(Value& v, const Pos& pos) {
forceValue(v); forceValue(v);
if (v.type != tBool) if (v.type != tBool) {
throwTypeError("value is %1% while a Boolean was expected, at %2%", v, pos); throwTypeError("value is %1% while a Boolean was expected, at %2%", v, pos);
}
return v.boolean; return v.boolean;
} }
@ -1391,20 +1422,22 @@ bool EvalState::isFunctor(Value& fun) {
void EvalState::forceFunction(Value& v, const Pos& pos) { void EvalState::forceFunction(Value& v, const Pos& pos) {
forceValue(v); forceValue(v);
if (v.type != tLambda && v.type != tPrimOp && v.type != tPrimOpApp && if (v.type != tLambda && v.type != tPrimOp && v.type != tPrimOpApp &&
!isFunctor(v)) !isFunctor(v)) {
throwTypeError("value is %1% while a function was expected, at %2%", v, throwTypeError("value is %1% while a function was expected, at %2%", v,
pos); pos);
}
} }
string EvalState::forceString(Value& v, const Pos& pos) { string EvalState::forceString(Value& v, const Pos& pos) {
forceValue(v, pos); forceValue(v, pos);
if (v.type != tString) { if (v.type != tString) {
if (pos) if (pos) {
throwTypeError("value is %1% while a string was expected, at %2%", v, throwTypeError("value is %1% while a string was expected, at %2%", v,
pos); pos);
else } else {
throwTypeError("value is %1% while a string was expected", v); throwTypeError("value is %1% while a string was expected", v);
} }
}
return string(v.string.s); return string(v.string.s);
} }
@ -1437,11 +1470,17 @@ string EvalState::forceStringNoCtx(Value& v, const Pos& pos) {
} }
bool EvalState::isDerivation(Value& v) { bool EvalState::isDerivation(Value& v) {
if (v.type != tAttrs) return false; if (v.type != tAttrs) {
return false;
}
Bindings::iterator i = v.attrs->find(sType); Bindings::iterator i = v.attrs->find(sType);
if (i == v.attrs->end()) return false; if (i == v.attrs->end()) {
return false;
}
forceValue(*i->value); forceValue(*i->value);
if (i->value->type != tString) return false; if (i->value->type != tString) {
return false;
}
return strcmp(i->value->string.s, "derivation") == 0; return strcmp(i->value->string.s, "derivation") == 0;
} }
@ -1556,14 +1595,22 @@ bool EvalState::eqValues(Value& v1, Value& v2) {
/* !!! Hack to support some old broken code that relies on pointer /* !!! Hack to support some old broken code that relies on pointer
equality tests between sets. (Specifically, builderDefs calls equality tests between sets. (Specifically, builderDefs calls
uniqList on a list of sets.) Will remove this eventually. */ uniqList on a list of sets.) Will remove this eventually. */
if (&v1 == &v2) return true; if (&v1 == &v2) {
return true;
}
// Special case type-compatibility between float and int // Special case type-compatibility between float and int
if (v1.type == tInt && v2.type == tFloat) return v1.integer == v2.fpoint; if (v1.type == tInt && v2.type == tFloat) {
if (v1.type == tFloat && v2.type == tInt) return v1.fpoint == v2.integer; return v1.integer == v2.fpoint;
}
if (v1.type == tFloat && v2.type == tInt) {
return v1.fpoint == v2.integer;
}
// All other types are not compatible with each other. // All other types are not compatible with each other.
if (v1.type != v2.type) return false; if (v1.type != v2.type) {
return false;
}
switch (v1.type) { switch (v1.type) {
case tInt: case tInt:
@ -1584,9 +1631,14 @@ bool EvalState::eqValues(Value& v1, Value& v2) {
case tList1: case tList1:
case tList2: case tList2:
case tListN: case tListN:
if (v1.listSize() != v2.listSize()) return false; if (v1.listSize() != v2.listSize()) {
for (size_t n = 0; n < v1.listSize(); ++n) return false;
if (!eqValues(*v1.listElems()[n], *v2.listElems()[n])) return false; }
for (size_t n = 0; n < v1.listSize(); ++n) {
if (!eqValues(*v1.listElems()[n], *v2.listElems()[n])) {
return false;
}
}
return true; return true;
case tAttrs: { case tAttrs: {
@ -1595,17 +1647,21 @@ bool EvalState::eqValues(Value& v1, Value& v2) {
if (isDerivation(v1) && isDerivation(v2)) { if (isDerivation(v1) && isDerivation(v2)) {
Bindings::iterator i = v1.attrs->find(sOutPath); Bindings::iterator i = v1.attrs->find(sOutPath);
Bindings::iterator j = v2.attrs->find(sOutPath); Bindings::iterator j = v2.attrs->find(sOutPath);
if (i != v1.attrs->end() && j != v2.attrs->end()) if (i != v1.attrs->end() && j != v2.attrs->end()) {
return eqValues(*i->value, *j->value); return eqValues(*i->value, *j->value);
} }
}
if (v1.attrs->size() != v2.attrs->size()) return false; if (v1.attrs->size() != v2.attrs->size()) {
return false;
}
/* Otherwise, compare the attributes one by one. */ /* Otherwise, compare the attributes one by one. */
Bindings::iterator i, j; Bindings::iterator i, j;
for (i = v1.attrs->begin(), j = v2.attrs->begin(); i != v1.attrs->end(); for (i = v1.attrs->begin(), j = v2.attrs->begin(); i != v1.attrs->end();
++i, ++j) ++i, ++j) {
if (i->name != j->name || !eqValues(*i->value, *j->value)) return false; if (i->name != j->name || !eqValues(*i->value, *j->value)) return false;
}
return true; return true;
} }

View file

@ -94,13 +94,16 @@ DrvInfo::Outputs DrvInfo::queryOutputs(bool onlyOutputsToInstall) {
string name = string name =
state->forceStringNoCtx(*i->value->listElems()[j], *i->pos); state->forceStringNoCtx(*i->value->listElems()[j], *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); state->forceAttrs(*out->value);
/* And evaluate its outPath attribute. */ /* And evaluate its outPath attribute. */
Bindings::iterator outPath = out->value->attrs->find(state->sOutPath); Bindings::iterator outPath = out->value->attrs->find(state->sOutPath);
if (outPath == out->value->attrs->end()) if (outPath == out->value->attrs->end()) {
continue; // FIXME: throw error? continue; // FIXME: throw error?
}
PathSet context; PathSet context;
outputs[name] = outputs[name] =
state->coerceToPath(*outPath->pos, *outPath->value, context); state->coerceToPath(*outPath->pos, *outPath->value, context);
@ -108,11 +111,15 @@ DrvInfo::Outputs DrvInfo::queryOutputs(bool onlyOutputsToInstall) {
} else } else
outputs["out"] = queryOutPath(); outputs["out"] = queryOutPath();
} }
if (!onlyOutputsToInstall || !attrs) return outputs; if (!onlyOutputsToInstall || !attrs) {
return outputs;
}
/* Check for `meta.outputsToInstall` and return `outputs` reduced to that. */ /* Check for `meta.outputsToInstall` and return `outputs` reduced to that. */
const Value* outTI = queryMeta("outputsToInstall"); const Value* outTI = queryMeta("outputsToInstall");
if (!outTI) return outputs; if (!outTI) {
return outputs;
}
const auto errMsg = Error("this derivation has bad 'meta.outputsToInstall'"); const auto errMsg = Error("this derivation has bad 'meta.outputsToInstall'");
/* ^ this shows during `nix-env -i` right under the bad derivation */ /* ^ this shows during `nix-env -i` right under the bad derivation */
if (!outTI->isList()) throw errMsg; if (!outTI->isList()) throw errMsg;
@ -136,10 +143,16 @@ string DrvInfo::queryOutputName() const {
} }
Bindings* DrvInfo::getMeta() { Bindings* DrvInfo::getMeta() {
if (meta) return meta; if (meta) {
if (!attrs) return 0; return meta;
}
if (!attrs) {
return 0;
}
Bindings::iterator a = attrs->find(state->sMeta); Bindings::iterator a = attrs->find(state->sMeta);
if (a == attrs->end()) return 0; if (a == attrs->end()) {
return 0;
}
state->forceAttrs(*a->value, *a->pos); state->forceAttrs(*a->value, *a->pos);
meta = a->value->attrs; meta = a->value->attrs;
return meta; return meta;
@ -147,7 +160,9 @@ Bindings* DrvInfo::getMeta() {
StringSet DrvInfo::queryMetaNames() { StringSet DrvInfo::queryMetaNames() {
StringSet res; StringSet res;
if (!getMeta()) return res; if (!getMeta()) {
return res;
}
for (auto& i : *meta) res.insert(i.name); for (auto& i : *meta) res.insert(i.name);
return res; return res;
} }
@ -155,24 +170,37 @@ StringSet DrvInfo::queryMetaNames() {
bool DrvInfo::checkMeta(Value& v) { bool DrvInfo::checkMeta(Value& v) {
state->forceValue(v); state->forceValue(v);
if (v.isList()) { if (v.isList()) {
for (unsigned int n = 0; n < v.listSize(); ++n) for (unsigned int n = 0; n < v.listSize(); ++n) {
if (!checkMeta(*v.listElems()[n])) return false; if (!checkMeta(*v.listElems()[n])) {
return false;
}
}
return true; return true;
} else if (v.type == tAttrs) { } else if (v.type == tAttrs) {
Bindings::iterator i = v.attrs->find(state->sOutPath); Bindings::iterator i = v.attrs->find(state->sOutPath);
if (i != v.attrs->end()) return false; if (i != v.attrs->end()) {
for (auto& i : *v.attrs) return false;
if (!checkMeta(*i.value)) return false; }
for (auto& i : *v.attrs) {
if (!checkMeta(*i.value)) {
return false;
}
}
return true; return true;
} else } else {
return v.type == tInt || v.type == tBool || v.type == tString || return v.type == tInt || v.type == tBool || v.type == tString ||
v.type == tFloat; v.type == tFloat;
}
} }
Value* DrvInfo::queryMeta(const string& name) { Value* DrvInfo::queryMeta(const 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));
if (a == meta->end() || !checkMeta(*a->value)) return 0; if (a == meta->end() || !checkMeta(*a->value)) {
return 0;
}
return a->value; return a->value;
} }
@ -184,8 +212,12 @@ string DrvInfo::queryMetaString(const string& name) {
NixInt DrvInfo::queryMetaInt(const string& name, NixInt def) { NixInt DrvInfo::queryMetaInt(const string& name, NixInt def) {
Value* v = queryMeta(name); Value* v = queryMeta(name);
if (!v) return def; if (!v) {
if (v->type == tInt) return v->integer; return def;
}
if (v->type == tInt) {
return v->integer;
}
if (v->type == tString) { if (v->type == tString) {
/* Backwards compatibility with before we had support for /* Backwards compatibility with before we had support for
integer meta fields. */ integer meta fields. */
@ -197,8 +229,12 @@ NixInt DrvInfo::queryMetaInt(const string& name, NixInt def) {
NixFloat DrvInfo::queryMetaFloat(const string& name, NixFloat def) { NixFloat DrvInfo::queryMetaFloat(const string& name, NixFloat def) {
Value* v = queryMeta(name); Value* v = queryMeta(name);
if (!v) return def; if (!v) {
if (v->type == tFloat) return v->fpoint; return def;
}
if (v->type == tFloat) {
return v->fpoint;
}
if (v->type == tString) { if (v->type == tString) {
/* Backwards compatibility with before we had support for /* Backwards compatibility with before we had support for
float meta fields. */ float meta fields. */
@ -210,8 +246,12 @@ NixFloat DrvInfo::queryMetaFloat(const string& name, NixFloat def) {
bool DrvInfo::queryMetaBool(const string& name, bool def) { bool DrvInfo::queryMetaBool(const string& name, bool def) {
Value* v = queryMeta(name); Value* v = queryMeta(name);
if (!v) return def; if (!v) {
if (v->type == tBool) return v->boolean; return def;
}
if (v->type == tBool) {
return v->boolean;
}
if (v->type == tString) { if (v->type == tString) {
/* Backwards compatibility with before we had support for /* Backwards compatibility with before we had support for
Boolean meta fields. */ Boolean meta fields. */
@ -226,10 +266,14 @@ void DrvInfo::setMeta(const string& name, Value* v) {
Bindings* old = meta; Bindings* old = meta;
meta = state->allocBindings(1 + (old ? old->size() : 0)); meta = state->allocBindings(1 + (old ? old->size() : 0));
Symbol sym = state->symbols.create(name); Symbol sym = state->symbols.create(name);
if (old) if (old) {
for (auto i : *old) for (auto i : *old) {
if (i.name != sym) meta->push_back(i); if (i.name != sym) meta->push_back(i);
if (v) meta->push_back(Attr(sym, v)); }
}
if (v) {
meta->push_back(Attr(sym, v));
}
meta->sort(); meta->sort();
} }
@ -245,7 +289,9 @@ static bool getDerivation(EvalState& state, Value& v, const string& attrPath,
bool ignoreAssertionFailures) { bool ignoreAssertionFailures) {
try { try {
state.forceValue(v); state.forceValue(v);
if (!state.isDerivation(v)) return true; if (!state.isDerivation(v)) {
return true;
}
/* Remove spurious duplicates (e.g., a set like `rec { x = /* Remove spurious duplicates (e.g., a set like `rec { x =
derivation {...}; y = x;}'. */ derivation {...}; y = x;}'. */
@ -261,7 +307,9 @@ static bool getDerivation(EvalState& state, Value& v, const string& attrPath,
return false; return false;
} catch (AssertionError& e) { } catch (AssertionError& e) {
if (ignoreAssertionFailures) return false; if (ignoreAssertionFailures) {
return false;
}
throw; throw;
} }
} }
@ -338,8 +386,10 @@ static void getDerivations(EvalState& state, Value& vIn,
} }
} }
else else {
throw TypeError( throw
}
TypeError(
"expression does not evaluate to a derivation (or a set or list of " "expression does not evaluate to a derivation (or a set or list of "
"those)"); "those)");
} }

View file

@ -5,7 +5,9 @@
namespace nix { namespace nix {
static void skipWhitespace(const char*& s) { static void skipWhitespace(const char*& s) {
while (*s == ' ' || *s == '\t' || *s == '\n' || *s == '\r') s++; while (*s == ' ' || *s == '\t' || *s == '\n' || *s == '\r') {
s++;
}
} }
static string parseJSONString(const char*& s) { static string parseJSONString(const char*& s) {
@ -39,8 +41,10 @@ static string parseJSONString(const char*& s) {
else else
throw JSONParseError("invalid escaped character in JSON string"); throw JSONParseError("invalid escaped character in JSON string");
s++; s++;
} else } else {
res += *s++; res
}
+= *s++;
} }
s++; s++;
return res; return res;
@ -62,7 +66,9 @@ static void parseJSON(EvalState& state, const char*& s, Value& v) {
parseJSON(state, s, *v2); parseJSON(state, s, *v2);
values.push_back(v2); values.push_back(v2);
skipWhitespace(s); skipWhitespace(s);
if (*s == ']') break; if (*s == ']') {
break;
}
if (*s != ',') if (*s != ',')
throw JSONParseError("expected ',' or ']' after JSON array element"); throw JSONParseError("expected ',' or ']' after JSON array element");
s++; s++;
@ -86,7 +92,9 @@ static void parseJSON(EvalState& state, const char*& s, Value& v) {
parseJSON(state, s, *v2); parseJSON(state, s, *v2);
attrs[state.symbols.create(name)] = v2; attrs[state.symbols.create(name)] = v2;
skipWhitespace(s); skipWhitespace(s);
if (*s == '}') break; if (*s == '}') {
break;
}
if (*s != ',') if (*s != ',')
throw JSONParseError("expected ',' or '}' after JSON member"); throw JSONParseError("expected ',' or '}' after JSON member");
s++; s++;

View file

@ -57,21 +57,23 @@ static bool componentsLT(const string& c1, const string& c2) {
int n1, n2; int n1, n2;
bool c1Num = string2Int(c1, n1), c2Num = string2Int(c2, n2); bool c1Num = string2Int(c1, n1), c2Num = string2Int(c2, n2);
if (c1Num && c2Num) if (c1Num && c2Num) {
return n1 < n2; return n1 < n2;
else if (c1 == "" && c2Num) } else if (c1 == "" && c2Num)
return true; return true;
else if (c1 == "pre" && c2 != "pre") else if (c1 == "pre" && c2 != "pre")
return true; return true;
else if (c2 == "pre") else if (c2 == "pre")
return false; return false;
/* Assume that `2.3a' < `2.3.1'. */ /* Assume that `2.3a' < `2.3.1'. */
else if (c2Num) else if (c2Num) {
return true; return true;
else if (c1Num) } else if (c1Num) {
return false; return false;
else } else {
return c1 < c2; return
}
c1 < c2;
} }
int compareVersions(const string& v1, const string& v2) { int compareVersions(const string& v1, const string& v2) {

View file

@ -208,7 +208,9 @@ void ExprVar::bindVars(const StaticEnv& env) {
int withLevel = -1; int withLevel = -1;
for (curEnv = &env, level = 0; curEnv; curEnv = curEnv->up, level++) { for (curEnv = &env, level = 0; curEnv; curEnv = curEnv->up, level++) {
if (curEnv->isWith) { if (curEnv->isWith) {
if (withLevel == -1) withLevel = level; if (withLevel == -1) {
withLevel = level;
}
} else { } else {
StaticEnv::Vars::const_iterator i = curEnv->vars.find(name); StaticEnv::Vars::const_iterator i = curEnv->vars.find(name);
if (i != curEnv->vars.end()) { if (i != curEnv->vars.end()) {
@ -233,7 +235,9 @@ void ExprVar::bindVars(const StaticEnv& env) {
void ExprSelect::bindVars(const StaticEnv& env) { void ExprSelect::bindVars(const StaticEnv& env) {
e->bindVars(env); e->bindVars(env);
if (def) def->bindVars(env); if (def) {
def->bindVars(env);
}
for (auto& i : attrPath) for (auto& i : attrPath)
if (!i.symbol.set()) i.expr->bindVars(env); if (!i.symbol.set()) i.expr->bindVars(env);
} }
@ -258,8 +262,10 @@ void ExprAttrs::bindVars(const StaticEnv& env) {
i.second.e->bindVars(i.second.inherited ? env : newEnv); i.second.e->bindVars(i.second.inherited ? env : newEnv);
} }
else else {
for (auto& i : attrs) i.second.e->bindVars(env); for
}
(auto& i : attrs) i.second.e->bindVars(env);
for (auto& i : dynamicAttrs) { for (auto& i : dynamicAttrs) {
i.nameExpr->bindVars(*dynamicEnv); i.nameExpr->bindVars(*dynamicEnv);
@ -307,11 +313,12 @@ void ExprWith::bindVars(const StaticEnv& env) {
const StaticEnv* curEnv; const StaticEnv* curEnv;
unsigned int level; unsigned int level;
prevWith = 0; prevWith = 0;
for (curEnv = &env, level = 1; curEnv; curEnv = curEnv->up, level++) for (curEnv = &env, level = 1; curEnv; curEnv = curEnv->up, level++) {
if (curEnv->isWith) { if (curEnv->isWith) {
prevWith = level; prevWith = level;
break; break;
} }
}
attrs->bindVars(env); attrs->bindVars(env);
StaticEnv newEnv(true, &env); StaticEnv newEnv(true, &env);

View file

@ -23,13 +23,25 @@ MakeError(EvalError, Error) MakeError(ParseError, Error)
: file(file), line(line), column(column){}; : file(file), line(line), column(column){};
operator bool() const { return line != 0; } operator bool() const { return line != 0; }
bool operator<(const Pos& p2) const { bool operator<(const Pos& p2) const {
if (!line) return p2.line; if (!line) {
if (!p2.line) return false; return p2.line;
}
if (!p2.line) {
return false;
}
int d = ((string)file).compare((string)p2.file); int d = ((string)file).compare((string)p2.file);
if (d < 0) return true; if (d < 0) {
if (d > 0) return false; return true;
if (line < p2.line) return true; }
if (line > p2.line) return false; if (d > 0) {
return false;
}
if (line < p2.line) {
return true;
}
if (line > p2.line) {
return false;
}
return column < p2.column; return column < p2.column;
} }
}; };

View file

@ -129,9 +129,9 @@ static void prim_scopedImport(EvalState& state, const Pos& pos, Value** args,
state.forceAttrs(v, pos); state.forceAttrs(v, pos);
} else { } else {
state.forceAttrs(*args[0]); state.forceAttrs(*args[0]);
if (args[0]->attrs->empty()) if (args[0]->attrs->empty()) {
state.evalFile(realPath, v); state.evalFile(realPath, v);
else { } else {
Env* env = &state.allocEnv(args[0]->attrs->size()); Env* env = &state.allocEnv(args[0]->attrs->size());
env->up = &state.baseEnv; env->up = &state.baseEnv;
@ -346,8 +346,12 @@ static void prim_isPath(EvalState& state, const Pos& pos, Value** args,
struct CompareValues { struct CompareValues {
bool operator()(const Value* v1, const Value* v2) const { bool operator()(const Value* v1, const Value* v2) const {
if (v1->type == tFloat && v2->type == tInt) return v1->fpoint < v2->integer; if (v1->type == tFloat && v2->type == tInt) {
if (v1->type == tInt && v2->type == tFloat) return v1->integer < v2->fpoint; return v1->fpoint < v2->integer;
}
if (v1->type == tInt && v2->type == tFloat) {
return v1->integer < v2->fpoint;
}
if (v1->type != v2->type) if (v1->type != v2->type)
throw EvalError(format("cannot compare %1% with %2%") % showType(*v1) % throw EvalError(format("cannot compare %1% with %2%") % showType(*v1) %
showType(*v2)); showType(*v2));
@ -562,8 +566,9 @@ static void prim_derivationStrict(EvalState& state, const Pos& pos,
/* Check whether null attributes should be ignored. */ /* Check whether null attributes should be ignored. */
bool ignoreNulls = false; bool ignoreNulls = false;
attr = args[0]->attrs->find(state.sIgnoreNulls); attr = args[0]->attrs->find(state.sIgnoreNulls);
if (attr != args[0]->attrs->end()) if (attr != args[0]->attrs->end()) {
ignoreNulls = state.forceBool(*attr->value, pos); ignoreNulls = state.forceBool(*attr->value, pos);
}
/* Build the derivation expression by processing the attributes. */ /* Build the derivation expression by processing the attributes. */
Derivation drv; Derivation drv;
@ -890,10 +895,11 @@ static void prim_dirOf(EvalState& state, const Pos& pos, Value** args,
Value& v) { Value& v) {
PathSet context; PathSet context;
Path dir = dirOf(state.coerceToString(pos, *args[0], context, false, false)); Path dir = dirOf(state.coerceToString(pos, *args[0], context, false, false));
if (args[0]->type == tPath) if (args[0]->type == tPath) {
mkPath(v, dir.c_str()); mkPath(v, dir.c_str());
else } else {
mkString(v, dir, context); mkString(v, dir, context);
}
} }
/* Return the contents of a file as a string. */ /* Return the contents of a file as a string. */
@ -1208,14 +1214,17 @@ static void prim_attrValues(EvalState& state, const Pos& pos, Value** args,
state.mkList(v, args[0]->attrs->size()); state.mkList(v, args[0]->attrs->size());
unsigned int n = 0; unsigned int n = 0;
for (auto& i : *args[0]->attrs) v.listElems()[n++] = (Value*)&i; for (auto& i : *args[0]->attrs) {
v.listElems()[n++] = (Value*)&i;
}
std::sort(v.listElems(), v.listElems() + n, [](Value* v1, Value* v2) { std::sort(v.listElems(), v.listElems() + n, [](Value* v1, Value* v2) {
return (string)((Attr*)v1)->name < (string)((Attr*)v2)->name; return (string)((Attr*)v1)->name < (string)((Attr*)v2)->name;
}); });
for (unsigned int i = 0; i < n; ++i) for (unsigned int i = 0; i < n; ++i) {
v.listElems()[i] = ((Attr*)v.listElems()[i])->value; v.listElems()[i] = ((Attr*)v.listElems()[i])->value;
}
} }
/* Dynamic version of the `.' operator. */ /* Dynamic version of the `.' operator. */
@ -1238,10 +1247,11 @@ void prim_unsafeGetAttrPos(EvalState& state, const Pos& pos, Value** args,
string attr = state.forceStringNoCtx(*args[0], pos); string attr = state.forceStringNoCtx(*args[0], pos);
state.forceAttrs(*args[1], pos); state.forceAttrs(*args[1], pos);
Bindings::iterator i = args[1]->attrs->find(state.symbols.create(attr)); Bindings::iterator i = args[1]->attrs->find(state.symbols.create(attr));
if (i == args[1]->attrs->end()) if (i == args[1]->attrs->end()) {
mkNull(v); mkNull(v);
else } else {
state.mkPos(v, i->pos); state.mkPos(v, i->pos);
}
} }
/* Dynamic version of the `?' operator. */ /* Dynamic version of the `?' operator. */
@ -1335,7 +1345,9 @@ static void prim_intersectAttrs(EvalState& state, const Pos& pos, Value** args,
for (auto& i : *args[0]->attrs) { for (auto& i : *args[0]->attrs) {
Bindings::iterator j = args[1]->attrs->find(i.name); Bindings::iterator j = args[1]->attrs->find(i.name);
if (j != args[1]->attrs->end()) v.attrs->push_back(*j); if (j != args[1]->attrs->end()) {
v.attrs->push_back(*j);
}
} }
} }
@ -1358,11 +1370,15 @@ static void prim_catAttrs(EvalState& state, const Pos& pos, Value** args,
Value& v2(*args[1]->listElems()[n]); Value& v2(*args[1]->listElems()[n]);
state.forceAttrs(v2, pos); state.forceAttrs(v2, pos);
Bindings::iterator i = v2.attrs->find(attrName); Bindings::iterator i = v2.attrs->find(attrName);
if (i != v2.attrs->end()) res[found++] = i->value; if (i != v2.attrs->end()) {
res[found++] = i->value;
}
} }
state.mkList(v, found); state.mkList(v, found);
for (unsigned int n = 0; n < found; ++n) v.listElems()[n] = res[n]; for (unsigned int n = 0; n < found; ++n) {
v.listElems()[n] = res[n];
}
} }
/* Return a set containing the names of the formal arguments expected /* Return a set containing the names of the formal arguments expected
@ -1454,8 +1470,9 @@ static void prim_tail(EvalState& state, const Pos& pos, Value** args,
if (args[0]->listSize() == 0) if (args[0]->listSize() == 0)
throw Error(format("'tail' called on an empty list, at %1%") % pos); throw Error(format("'tail' called on an empty list, at %1%") % pos);
state.mkList(v, args[0]->listSize() - 1); state.mkList(v, args[0]->listSize() - 1);
for (unsigned int n = 0; n < v.listSize(); ++n) for (unsigned int n = 0; n < v.listSize(); ++n) {
v.listElems()[n] = args[0]->listElems()[n + 1]; v.listElems()[n] = args[0]->listElems()[n + 1];
}
} }
/* Apply a function to every element of a list. */ /* Apply a function to every element of a list. */
@ -1464,9 +1481,10 @@ static void prim_map(EvalState& state, const Pos& pos, Value** args, Value& v) {
state.mkList(v, args[1]->listSize()); state.mkList(v, args[1]->listSize());
for (unsigned int n = 0; n < v.listSize(); ++n) for (unsigned int n = 0; n < v.listSize(); ++n) {
mkApp(*(v.listElems()[n] = state.allocValue()), *args[0], mkApp(*(v.listElems()[n] = state.allocValue()), *args[0],
*args[1]->listElems()[n]); *args[1]->listElems()[n]);
}
} }
/* Filter a list using a predicate; that is, return a list containing /* Filter a list using a predicate; that is, return a list containing
@ -1485,17 +1503,20 @@ static void prim_filter(EvalState& state, const Pos& pos, Value** args,
for (unsigned int n = 0; n < args[1]->listSize(); ++n) { for (unsigned int n = 0; n < args[1]->listSize(); ++n) {
Value res; Value res;
state.callFunction(*args[0], *args[1]->listElems()[n], res, noPos); state.callFunction(*args[0], *args[1]->listElems()[n], res, noPos);
if (state.forceBool(res, pos)) if (state.forceBool(res, pos)) {
vs[k++] = args[1]->listElems()[n]; vs[k++] = args[1]->listElems()[n];
else } else {
same = false; same = false;
} }
}
if (same) if (same) {
v = *args[1]; v = *args[1];
else { } else {
state.mkList(v, k); state.mkList(v, k);
for (unsigned int n = 0; n < k; ++n) v.listElems()[n] = vs[n]; for (unsigned int n = 0; n < k; ++n) {
v.listElems()[n] = vs[n];
}
} }
} }
@ -1504,11 +1525,12 @@ static void prim_elem(EvalState& state, const Pos& pos, Value** args,
Value& v) { Value& v) {
bool res = false; bool res = false;
state.forceList(*args[1], pos); state.forceList(*args[1], pos);
for (unsigned int n = 0; n < args[1]->listSize(); ++n) for (unsigned int n = 0; n < args[1]->listSize(); ++n) {
if (state.eqValues(*args[0], *args[1]->listElems()[n])) { if (state.eqValues(*args[0], *args[1]->listElems()[n])) {
res = true; res = true;
break; break;
} }
}
mkBool(v, res); mkBool(v, res);
} }
@ -1610,8 +1632,9 @@ static void prim_sort(EvalState& state, const Pos& pos, Value** args,
auto comparator = [&](Value* a, Value* b) { auto comparator = [&](Value* a, Value* b) {
/* Optimization: if the comparator is lessThan, bypass /* Optimization: if the comparator is lessThan, bypass
callFunction. */ callFunction. */
if (args[0]->type == tPrimOp && args[0]->primOp->fun == prim_lessThan) if (args[0]->type == tPrimOp && args[0]->primOp->fun == prim_lessThan) {
return CompareValues()(a, b); return CompareValues()(a, b);
}
Value vTmp1, vTmp2; Value vTmp1, vTmp2;
state.callFunction(*args[0], *a, vTmp1, pos); state.callFunction(*args[0], *a, vTmp1, pos);
@ -1694,31 +1717,34 @@ static void prim_concatMap(EvalState& state, const Pos& pos, Value** args,
static void prim_add(EvalState& state, const Pos& pos, Value** args, Value& v) { static void prim_add(EvalState& state, const Pos& pos, Value** args, Value& v) {
state.forceValue(*args[0], pos); state.forceValue(*args[0], pos);
state.forceValue(*args[1], pos); state.forceValue(*args[1], pos);
if (args[0]->type == tFloat || args[1]->type == tFloat) if (args[0]->type == tFloat || args[1]->type == tFloat) {
mkFloat(v, mkFloat(v,
state.forceFloat(*args[0], pos) + state.forceFloat(*args[1], pos)); state.forceFloat(*args[0], pos) + state.forceFloat(*args[1], pos));
else } else {
mkInt(v, state.forceInt(*args[0], pos) + state.forceInt(*args[1], pos)); mkInt(v, state.forceInt(*args[0], pos) + state.forceInt(*args[1], pos));
}
} }
static void prim_sub(EvalState& state, const Pos& pos, Value** args, Value& v) { static void prim_sub(EvalState& state, const Pos& pos, Value** args, Value& v) {
state.forceValue(*args[0], pos); state.forceValue(*args[0], pos);
state.forceValue(*args[1], pos); state.forceValue(*args[1], pos);
if (args[0]->type == tFloat || args[1]->type == tFloat) if (args[0]->type == tFloat || args[1]->type == tFloat) {
mkFloat(v, mkFloat(v,
state.forceFloat(*args[0], pos) - state.forceFloat(*args[1], pos)); state.forceFloat(*args[0], pos) - state.forceFloat(*args[1], pos));
else } else {
mkInt(v, state.forceInt(*args[0], pos) - state.forceInt(*args[1], pos)); mkInt(v, state.forceInt(*args[0], pos) - state.forceInt(*args[1], pos));
}
} }
static void prim_mul(EvalState& state, const Pos& pos, Value** args, Value& v) { static void prim_mul(EvalState& state, const Pos& pos, Value** args, Value& v) {
state.forceValue(*args[0], pos); state.forceValue(*args[0], pos);
state.forceValue(*args[1], pos); state.forceValue(*args[1], pos);
if (args[0]->type == tFloat || args[1]->type == tFloat) if (args[0]->type == tFloat || args[1]->type == tFloat) {
mkFloat(v, mkFloat(v,
state.forceFloat(*args[0], pos) * state.forceFloat(*args[1], pos)); state.forceFloat(*args[0], pos) * state.forceFloat(*args[1], pos));
else } else {
mkInt(v, state.forceInt(*args[0], pos) * state.forceInt(*args[1], pos)); mkInt(v, state.forceInt(*args[0], pos) * state.forceInt(*args[1], pos));
}
} }
static void prim_div(EvalState& state, const Pos& pos, Value** args, Value& v) { static void prim_div(EvalState& state, const Pos& pos, Value** args, Value& v) {
@ -1937,10 +1963,12 @@ static void prim_concatStringSep(EvalState& state, const Pos& pos, Value** args,
bool first = true; bool first = true;
for (unsigned int n = 0; n < args[1]->listSize(); ++n) { for (unsigned int n = 0; n < args[1]->listSize(); ++n) {
if (first) if (first) {
first = false; first = false;
else } else {
res += sep; res
}
+= sep;
res += state.coerceToString(pos, *args[1]->listElems()[n], context); res += state.coerceToString(pos, *args[1]->listElems()[n], context);
} }
@ -2074,8 +2102,10 @@ void fetch(EvalState& state, const Pos& pos, Value** args, Value& v,
if (request.uri.empty()) if (request.uri.empty())
throw EvalError(format("'url' argument required, at %1%") % pos); throw EvalError(format("'url' argument required, at %1%") % pos);
} else } else {
request.uri = state.forceStringNoCtx(*args[0], pos); request
}
.uri = state.forceStringNoCtx(*args[0], pos);
state.checkURI(request.uri); state.checkURI(request.uri);

View file

@ -227,8 +227,10 @@ static void prim_fetchGit(EvalState& state, const Pos& pos, Value** args,
if (url.empty()) if (url.empty())
throw EvalError(format("'url' argument required, at %1%") % pos); throw EvalError(format("'url' argument required, at %1%") % pos);
} else } else {
url = state.coerceToString(pos, *args[0], context, false, false); url
}
= state.coerceToString(pos, *args[0], context, false, false);
// FIXME: git externals probably can be used to bypass the URI // FIXME: git externals probably can be used to bypass the URI
// whitelist. Ah well. // whitelist. Ah well.

View file

@ -203,8 +203,10 @@ static void prim_fetchMercurial(EvalState& state, const Pos& pos, Value** args,
if (url.empty()) if (url.empty())
throw EvalError(format("'url' argument required, at %1%") % pos); throw EvalError(format("'url' argument required, at %1%") % pos);
} else } else {
url = state.coerceToString(pos, *args[0], context, false, false); url
}
= state.coerceToString(pos, *args[0], context, false, false);
// FIXME: git externals probably can be used to bypass the URI // FIXME: git externals probably can be used to bypass the URI
// whitelist. Ah well. // whitelist. Ah well.

View file

@ -13,7 +13,9 @@ void printValueAsJSON(EvalState& state, bool strict, Value& v,
JSONPlaceholder& out, PathSet& context) { JSONPlaceholder& out, PathSet& context) {
checkInterrupt(); checkInterrupt();
if (strict) state.forceValue(v); if (strict) {
state.forceValue(v);
}
switch (v.type) { switch (v.type) {
case tInt: case tInt:

View file

@ -48,7 +48,9 @@ static void printValueAsXML(EvalState& state, bool strict, bool location,
PathSet& drvsSeen) { PathSet& drvsSeen) {
checkInterrupt(); checkInterrupt();
if (strict) state.forceValue(v); if (strict) {
state.forceValue(v);
}
switch (v.type) { switch (v.type) {
case tInt: case tInt:
@ -85,14 +87,18 @@ static void printValueAsXML(EvalState& state, bool strict, bool location,
Path drvPath; Path drvPath;
a = v.attrs->find(state.sDrvPath); a = v.attrs->find(state.sDrvPath);
if (a != v.attrs->end()) { if (a != v.attrs->end()) {
if (strict) state.forceValue(*a->value); if (strict) {
state.forceValue(*a->value);
}
if (a->value->type == tString) if (a->value->type == tString)
xmlAttrs["drvPath"] = drvPath = a->value->string.s; xmlAttrs["drvPath"] = drvPath = a->value->string.s;
} }
a = v.attrs->find(state.sOutPath); a = v.attrs->find(state.sOutPath);
if (a != v.attrs->end()) { if (a != v.attrs->end()) {
if (strict) state.forceValue(*a->value); if (strict) {
state.forceValue(*a->value);
}
if (a->value->type == tString) if (a->value->type == tString)
xmlAttrs["outPath"] = a->value->string.s; xmlAttrs["outPath"] = a->value->string.s;
} }
@ -117,9 +123,10 @@ static void printValueAsXML(EvalState& state, bool strict, bool location,
case tList2: case tList2:
case tListN: { case tListN: {
XMLOpenElement _(doc, "list"); XMLOpenElement _(doc, "list");
for (unsigned int n = 0; n < v.listSize(); ++n) for (unsigned int n = 0; n < v.listSize(); ++n) {
printValueAsXML(state, strict, location, *v.listElems()[n], doc, printValueAsXML(state, strict, location, *v.listElems()[n], doc,
context, drvsSeen); context, drvsSeen);
}
break; break;
} }
@ -135,9 +142,10 @@ static void printValueAsXML(EvalState& state, bool strict, bool location,
XMLOpenElement _(doc, "attrspat", attrs); XMLOpenElement _(doc, "attrspat", attrs);
for (auto& i : v.lambda.fun->formals->formals) for (auto& i : v.lambda.fun->formals->formals)
doc.writeEmptyElement("attr", singletonAttrs("name", i.name)); doc.writeEmptyElement("attr", singletonAttrs("name", i.name));
} else } else {
doc.writeEmptyElement("varpat", doc
singletonAttrs("name", v.lambda.fun->arg)); }
.writeEmptyElement("varpat", singletonAttrs("name", v.lambda.fun->arg));
break; break;
} }

View file

@ -23,7 +23,9 @@ namespace nix {
static bool gcWarning = true; static bool gcWarning = true;
void printGCWarning() { void printGCWarning() {
if (!gcWarning) return; if (!gcWarning) {
return;
}
static bool haveWarned = false; static bool haveWarned = false;
if (!haveWarned) { if (!haveWarned) {

View file

@ -59,16 +59,18 @@ N getIntArg(const string& opt, Strings::iterator& i,
if (allowUnit && !s.empty()) { if (allowUnit && !s.empty()) {
char u = std::toupper(*s.rbegin()); char u = std::toupper(*s.rbegin());
if (std::isalpha(u)) { if (std::isalpha(u)) {
if (u == 'K') if (u == 'K') {
multiplier = 1ULL << 10; multiplier = 1ULL << 10;
else if (u == 'M') } else if (u == 'M') {
multiplier = 1ULL << 20; multiplier = 1ULL << 20;
else if (u == 'G') } else if (u == 'G') {
multiplier = 1ULL << 30; multiplier = 1ULL << 30;
else if (u == 'T') } else if (u == 'T') {
multiplier = 1ULL << 40; multiplier = 1ULL << 40;
else } else {
throw UsageError(format("invalid unit specifier '%1%'") % u); throw
}
UsageError(format("invalid unit specifier '%1%'") % u);
s.resize(s.size() - 1); s.resize(s.size() - 1);
} }
} }

View file

@ -350,12 +350,17 @@ void Goal::waiteeDone(GoalPtr waitee, ExitCode result) {
trace(format("waitee '%1%' done; %2% left") % waitee->name % waitees.size()); trace(format("waitee '%1%' done; %2% left") % waitee->name % waitees.size());
if (result == ecFailed || result == ecNoSubstituters || if (result == ecFailed || result == ecNoSubstituters ||
result == ecIncompleteClosure) result == ecIncompleteClosure) {
++nrFailed; ++nrFailed;
}
if (result == ecNoSubstituters) ++nrNoSubstituters; if (result == ecNoSubstituters) {
++nrNoSubstituters;
}
if (result == ecIncompleteClosure) ++nrIncompleteClosure; if (result == ecIncompleteClosure) {
++nrIncompleteClosure;
}
if (waitees.empty() || (result == ecFailed && !settings.keepGoing)) { if (waitees.empty() || (result == ecFailed && !settings.keepGoing)) {
/* If we failed and keepGoing is not set, we remove all /* If we failed and keepGoing is not set, we remove all
@ -1147,7 +1152,9 @@ void DerivationGoal::outputsSubstituted() {
/* If the substitutes form an incomplete closure, then we should /* If the substitutes form an incomplete closure, then we should
build the dependencies of this derivation, but after that, we build the dependencies of this derivation, but after that, we
can still use the substitutes for this derivation itself. */ can still use the substitutes for this derivation itself. */
if (nrIncompleteClosure > 0) retrySubstitution = true; if (nrIncompleteClosure > 0) {
retrySubstitution = true;
}
nrFailed = nrNoSubstituters = nrIncompleteClosure = 0; nrFailed = nrNoSubstituters = nrIncompleteClosure = 0;
@ -1659,7 +1666,9 @@ MakeError(NotDeterministic, BuildError)
} }
HookReply DerivationGoal::tryBuildHook() { HookReply DerivationGoal::tryBuildHook() {
if (!worker.tryBuildHook || !useDerivation) return rpDecline; if (!worker.tryBuildHook || !useDerivation) {
return rpDecline;
}
if (!worker.hook) worker.hook = std::make_unique<HookInstance>(); if (!worker.hook) worker.hook = std::make_unique<HookInstance>();
@ -2231,7 +2240,9 @@ void DerivationGoal::startBuilder() {
us. us.
*/ */
if (!fixedOutput) privateNetwork = true; if (!fixedOutput) {
privateNetwork = true;
}
userNamespaceSync.create(); userNamespaceSync.create();
@ -3117,7 +3128,9 @@ void DerivationGoal::registerOutputs() {
bool allValid = true; bool allValid = true;
for (auto& i : drv->outputs) for (auto& i : drv->outputs)
if (!worker.store.isValidPath(i.second.path)) allValid = false; if (!worker.store.isValidPath(i.second.path)) allValid = false;
if (allValid) return; if (allValid) {
return;
}
} }
std::map<std::string, ValidPathInfo> infos; std::map<std::string, ValidPathInfo> infos;
@ -3345,7 +3358,9 @@ void DerivationGoal::registerOutputs() {
infos[i.first] = info; infos[i.first] = info;
} }
if (buildMode == bmCheck) return; if (buildMode == bmCheck) {
return;
}
/* Apply output checks. */ /* Apply output checks. */
checkOutputs(infos); checkOutputs(infos);
@ -4095,9 +4110,10 @@ GoalPtr Worker::makeDerivationGoal(const Path& path,
std::make_shared<DerivationGoal>(path, wantedOutputs, *this, buildMode); std::make_shared<DerivationGoal>(path, wantedOutputs, *this, buildMode);
derivationGoals[path] = goal; derivationGoals[path] = goal;
wakeUp(goal); wakeUp(goal);
} else } else {
(dynamic_cast<DerivationGoal*>(goal.get())) (dynamic_cast<DerivationGoal*>(goal.get()))
->addWantedOutputs(wantedOutputs); ->addWantedOutputs(wantedOutputs);
}
return goal; return goal;
} }
@ -4167,7 +4183,9 @@ void Worker::childStarted(GoalPtr goal, const set<int>& fds, bool inBuildSlot,
child.inBuildSlot = inBuildSlot; child.inBuildSlot = inBuildSlot;
child.respectTimeouts = respectTimeouts; child.respectTimeouts = respectTimeouts;
children.emplace_back(child); children.emplace_back(child);
if (inBuildSlot) nrLocalBuilds++; if (inBuildSlot) {
nrLocalBuilds++;
}
} }
void Worker::childTerminated(Goal* goal, bool wakeSleepers) { void Worker::childTerminated(Goal* goal, bool wakeSleepers) {
@ -4413,14 +4431,22 @@ unsigned int Worker::exitStatus() {
*/ */
unsigned int mask = 0; unsigned int mask = 0;
bool buildFailure = permanentFailure || timedOut || hashMismatch; bool buildFailure = permanentFailure || timedOut || hashMismatch;
if (buildFailure) mask |= 0x04; // 100 if (buildFailure) {
if (timedOut) mask |= 0x01; // 101 mask |= 0x04; // 100
if (hashMismatch) mask |= 0x02; // 102 }
if (timedOut) {
mask |= 0x01; // 101
}
if (hashMismatch) {
mask |= 0x02; // 102
}
if (checkMismatch) { if (checkMismatch) {
mask |= 0x08; // 104 mask |= 0x08; // 104
} }
if (mask) mask |= 0x60; if (mask) {
mask |= 0x60;
}
return mask ? mask : 1; return mask ? mask : 1;
} }
@ -4430,9 +4456,9 @@ bool Worker::pathContentsGood(const Path& path) {
LOG(INFO) << "checking path '" << path << "'..."; LOG(INFO) << "checking path '" << path << "'...";
auto info = store.queryPathInfo(path); auto info = store.queryPathInfo(path);
bool res; bool res;
if (!pathExists(path)) if (!pathExists(path)) {
res = false; res = false;
else { } else {
HashResult current = hashPath(info->narHash.type, path); HashResult current = hashPath(info->narHash.type, path);
Hash nullHash(htSHA256); Hash nullHash(htSHA256);
res = info->narHash == nullHash || info->narHash == current.first; res = info->narHash == nullHash || info->narHash == current.first;

View file

@ -185,19 +185,21 @@ Derivation Store::derivationFromPath(const Path& drvPath) {
static void printString(string& res, const string& s) { static void printString(string& res, const string& s) {
res += '"'; res += '"';
for (const char* i = s.c_str(); *i; i++) for (const char* i = s.c_str(); *i; i++) {
if (*i == '\"' || *i == '\\') { if (*i == '\"' || *i == '\\') {
res += "\\"; res += "\\";
res += *i; res += *i;
} else if (*i == '\n') } else if (*i == '\n') {
res += "\\n"; res += "\\n";
else if (*i == '\r') } else if (*i == '\r') {
res += "\\r"; res += "\\r";
else if (*i == '\t') } else if (*i == '\t') {
res += "\\t"; res += "\\t";
else } else {
res += *i; res += *i;
}
res += '"'; res += '"';
}
} }
template <class ForwardIterator> template <class ForwardIterator>
@ -205,10 +207,11 @@ static void printStrings(string& res, ForwardIterator i, ForwardIterator j) {
res += '['; res += '[';
bool first = true; bool first = true;
for (; i != j; ++i) { for (; i != j; ++i) {
if (first) if (first) {
first = false; first = false;
else } else {
res += ','; res += ',';
}
printString(res, *i); printString(res, *i);
} }
res += ']'; res += ']';

View file

@ -108,10 +108,14 @@ struct CurlDownloader : public Downloader {
~DownloadItem() { ~DownloadItem() {
if (req) { if (req) {
if (active) curl_multi_remove_handle(downloader.curlm, req); if (active) {
curl_multi_remove_handle(downloader.curlm, req);
}
curl_easy_cleanup(req); curl_easy_cleanup(req);
} }
if (requestHeaders) curl_slist_free_all(requestHeaders); if (requestHeaders) {
curl_slist_free_all(requestHeaders);
}
try { try {
if (!done) if (!done)
fail(DownloadError( fail(DownloadError(
@ -242,7 +246,9 @@ struct CurlDownloader : public Downloader {
} }
void init() { void init() {
if (!req) req = curl_easy_init(); if (!req) {
req = curl_easy_init();
}
curl_easy_reset(req); curl_easy_reset(req);
@ -316,8 +322,9 @@ struct CurlDownloader : public Downloader {
settings.netrcFile.get().c_str()); settings.netrcFile.get().c_str());
curl_easy_setopt(req, CURLOPT_NETRC, CURL_NETRC_OPTIONAL); curl_easy_setopt(req, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
if (writtenToSink) if (writtenToSink) {
curl_easy_setopt(req, CURLOPT_RESUME_FROM_LARGE, writtenToSink); curl_easy_setopt(req, CURLOPT_RESUME_FROM_LARGE, writtenToSink);
}
result.data = std::make_shared<std::string>(); result.data = std::make_shared<std::string>();
result.bodySize = 0; result.bodySize = 0;
@ -505,7 +512,9 @@ struct CurlDownloader : public Downloader {
workerThread.join(); workerThread.join();
if (curlm) curl_multi_cleanup(curlm); if (curlm) {
curl_multi_cleanup(curlm);
}
} }
void stopWorkerThread() { void stopWorkerThread() {

View file

@ -630,7 +630,9 @@ void LocalStore::tryToDelete(GCState& state, const Path& path) {
nix-store --delete doesn't have the unexpected effect of nix-store --delete doesn't have the unexpected effect of
recursing into derivations and outputs. */ recursing into derivations and outputs. */
state.dead.insert(visited.begin(), visited.end()); state.dead.insert(visited.begin(), visited.end());
if (state.shouldDelete) deletePathRecursive(state, path); if (state.shouldDelete) {
deletePathRecursive(state, path);
}
} }
} }
@ -704,7 +706,9 @@ void LocalStore::collectGarbage(const GCOptions& options, GCResults& results) {
state.shouldDelete = options.action == GCOptions::gcDeleteDead || state.shouldDelete = options.action == GCOptions::gcDeleteDead ||
options.action == GCOptions::gcDeleteSpecific; options.action == GCOptions::gcDeleteSpecific;
if (state.shouldDelete) deletePath(reservedPath); if (state.shouldDelete) {
deletePath(reservedPath);
}
/* Acquire the global GC root. This prevents /* Acquire the global GC root. This prevents
a) New roots from being added. a) New roots from being added.
@ -737,7 +741,9 @@ void LocalStore::collectGarbage(const GCOptions& options, GCResults& results) {
that is not reachable from `roots' is garbage. */ that is not reachable from `roots' is garbage. */
if (state.shouldDelete) { if (state.shouldDelete) {
if (pathExists(trashDir)) deleteGarbage(state, trashDir); if (pathExists(trashDir)) {
deleteGarbage(state, trashDir);
}
try { try {
createDirs(trashDir); createDirs(trashDir);
} catch (SysError& e) { } catch (SysError& e) {

View file

@ -77,8 +77,9 @@ class HttpBinaryCacheStore : public BinaryCacheStore {
} catch (DownloadError& e) { } catch (DownloadError& e) {
/* S3 buckets return 403 if a file doesn't exist and the /* S3 buckets return 403 if a file doesn't exist and the
bucket is unlistable, so treat 403 as 404. */ bucket is unlistable, so treat 403 as 404. */
if (e.error == Downloader::NotFound || e.error == Downloader::Forbidden) if (e.error == Downloader::NotFound || e.error == Downloader::Forbidden) {
return false; return false;
}
maybeDisable(); maybeDisable();
throw; throw;
} }

View file

@ -96,10 +96,10 @@ std::shared_ptr<std::string> LocalFSStore::getBuildLog(const Path& path_) {
: fmt("%s/%s/%s", logDir, drvsLogDir, baseName); : fmt("%s/%s/%s", logDir, drvsLogDir, baseName);
Path logBz2Path = logPath + ".bz2"; Path logBz2Path = logPath + ".bz2";
if (pathExists(logPath)) if (pathExists(logPath)) {
return std::make_shared<std::string>(readFile(logPath)); return std::make_shared<std::string>(readFile(logPath));
else if (pathExists(logBz2Path)) { } else if (pathExists(logBz2Path)) {
try { try {
return decompress("bzip2", readFile(logBz2Path)); return decompress("bzip2", readFile(logBz2Path));
} catch (Error&) { } catch (Error&) {

View file

@ -157,19 +157,17 @@ LocalStore::LocalStore(const Params& params)
/* Check the current database schema and if necessary do an /* Check the current database schema and if necessary do an
upgrade. */ upgrade. */
int curSchema = getSchema(); int curSchema = getSchema();
if (curSchema > nixSchemaVersion) if (curSchema > nixSchemaVersion) {
throw Error( throw Error(
format( format(
"current Nix store schema is version %1%, but I only support %2%") % "current Nix store schema is version %1%, but I only support %2%") %
curSchema % nixSchemaVersion); curSchema % nixSchemaVersion);
else if (curSchema == 0) { /* new store */ } else if (curSchema == 0) { /* new store */
curSchema = nixSchemaVersion; curSchema = nixSchemaVersion;
openDB(*state, true); openDB(*state, true);
writeFile(schemaPath, (format("%1%") % nixSchemaVersion).str()); writeFile(schemaPath, (format("%1%") % nixSchemaVersion).str());
} } else if (curSchema < nixSchemaVersion) {
else if (curSchema < nixSchemaVersion) {
if (curSchema < 5) if (curSchema < 5)
throw Error( throw Error(
"Your Nix store has a database in Berkeley DB format,\n" "Your Nix store has a database in Berkeley DB format,\n"
@ -219,10 +217,9 @@ LocalStore::LocalStore(const Params& params)
writeFile(schemaPath, (format("%1%") % nixSchemaVersion).str()); writeFile(schemaPath, (format("%1%") % nixSchemaVersion).str());
lockFile(globalLock.get(), ltRead, true); lockFile(globalLock.get(), ltRead, true);
} } else {
else
openDB(*state, false); openDB(*state, false);
}
/* Prepare SQL statements. */ /* Prepare SQL statements. */
state->stmtRegisterValidPath.create( state->stmtRegisterValidPath.create(
@ -325,8 +322,9 @@ void LocalStore::openDB(State& state, bool create) {
SetDllDirectoryW(L""); SetDllDirectoryW(L"");
#endif #endif
if (sqlite3_busy_timeout(db, 60 * 60 * 1000) != SQLITE_OK) if (sqlite3_busy_timeout(db, 60 * 60 * 1000) != SQLITE_OK) {
throwSQLiteError(db, "setting timeout"); throwSQLiteError(db, "setting timeout");
}
db.exec("pragma foreign_keys = 1"); db.exec("pragma foreign_keys = 1");
@ -347,8 +345,9 @@ void LocalStore::openDB(State& state, bool create) {
{ {
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 = string((const char*)sqlite3_column_text(stmt, 0));
} }
if (prevMode != mode && if (prevMode != mode &&
@ -622,7 +621,9 @@ uint64_t LocalStore::addValidPath(State& state, const ValidPathInfo& info,
derivations). Note that if this throws an error, then the derivations). Note that if this throws an error, then the
DB transaction is rolled back, so the path validity DB transaction is rolled back, so the path validity
registration above is undone. */ registration above is undone. */
if (checkOutputs) checkDerivationOutputs(info.path, drv); if (checkOutputs) {
checkDerivationOutputs(info.path, drv);
}
for (auto& i : drv.outputs) { for (auto& i : drv.outputs) {
state.stmtAddDerivationOutput.use()(id)(i.first)(i.second.path).exec(); state.stmtAddDerivationOutput.use()(id)(i.first)(i.second.path).exec();
@ -1046,8 +1047,9 @@ Path LocalStore::addToStoreFromDump(const string& dump, const string& name,
if (recursive) { if (recursive) {
StringSource source(dump); StringSource source(dump);
restorePath(realPath, source); restorePath(realPath, source);
} else } else {
writeFile(realPath, dump); writeFile(realPath, dump);
}
canonicalisePathMetaData(realPath, -1); canonicalisePathMetaData(realPath, -1);
@ -1059,8 +1061,9 @@ Path LocalStore::addToStoreFromDump(const string& dump, const string& name,
if (recursive) { if (recursive) {
hash.first = hashAlgo == htSHA256 ? h : hashString(htSHA256, dump); hash.first = hashAlgo == htSHA256 ? h : hashString(htSHA256, dump);
hash.second = dump.size(); hash.second = dump.size();
} else } else {
hash = hashPath(htSHA256, realPath); hash = hashPath(htSHA256, realPath);
}
optimisePath(realPath); // FIXME: combine with hashPath() optimisePath(realPath); // FIXME: combine with hashPath()
@ -1297,15 +1300,17 @@ void LocalStore::verifyPath(const Path& path, const PathSet& store,
} else { } else {
LOG(ERROR) << "path '" << path LOG(ERROR) << "path '" << path
<< "' disappeared, but it still has valid referrers!"; << "' disappeared, but it still has valid referrers!";
if (repair) try { if (repair) {
try {
repairPath(path); repairPath(path);
} catch (Error& e) { } catch (Error& e) {
LOG(WARNING) << e.msg(); LOG(WARNING) << e.msg();
errors = true; errors = true;
} }
else } else {
errors = true; errors = true;
} }
}
return; return;
} }

View file

@ -206,7 +206,9 @@ retry:
the store itself (we don't want or need to mess with its the store itself (we don't want or need to mess with its
permissions). */ permissions). */
bool mustToggle = dirOf(path) != realStoreDir; bool mustToggle = dirOf(path) != realStoreDir;
if (mustToggle) makeWritable(dirOf(path)); if (mustToggle) {
makeWritable(dirOf(path));
}
/* When we're done, make the directory read-only again and reset /* When we're done, make the directory read-only again and reset
its timestamp back to 0. */ its timestamp back to 0. */

View file

@ -18,7 +18,9 @@ static void search(const unsigned char* s, size_t len, StringSet& hashes,
static bool initialised = false; static bool initialised = false;
static bool isBase32[256]; static bool isBase32[256];
if (!initialised) { if (!initialised) {
for (unsigned int i = 0; i < 256; ++i) isBase32[i] = false; for (unsigned int i = 0; i < 256; ++i) {
isBase32[i] = false;
}
for (unsigned int i = 0; i < base32Chars.size(); ++i) for (unsigned int i = 0; i < base32Chars.size(); ++i)
isBase32[(unsigned char)base32Chars[i]] = true; isBase32[(unsigned char)base32Chars[i]] = true;
initialised = true; initialised = true;

View file

@ -33,7 +33,9 @@ Path readStorePath(Store& store, Source& from) {
template <class T> template <class T>
T readStorePaths(Store& store, Source& from) { T readStorePaths(Store& store, Source& from) {
T paths = readStrings<T>(from); T paths = readStrings<T>(from);
for (auto& i : paths) store.assertStorePath(i); for (auto& i : paths) {
store.assertStorePath(i);
}
return paths; return paths;
} }
@ -600,10 +602,11 @@ void RemoteStore::queryMissing(const PathSet& targets, PathSet& willBuild,
unsigned long long& narSize) { unsigned long long& narSize) {
{ {
auto conn(getConnection()); auto conn(getConnection());
if (GET_PROTOCOL_MINOR(conn->daemonVersion) < 19) if (GET_PROTOCOL_MINOR(conn->daemonVersion) < 19) {
// Don't hold the connection handle in the fallback case // Don't hold the connection handle in the fallback case
// to prevent a deadlock. // to prevent a deadlock.
goto fallback; goto fallback;
}
conn->to << wopQueryMissing << targets; conn->to << wopQueryMissing << targets;
conn.processStderr(); conn.processStderr();
willBuild = readStorePaths<PathSet>(*this, conn->from); willBuild = readStorePaths<PathSet>(*this, conn->from);

View file

@ -14,15 +14,19 @@ namespace nix {
int exterr = sqlite3_extended_errcode(db); int exterr = sqlite3_extended_errcode(db);
auto path = sqlite3_db_filename(db, nullptr); auto path = sqlite3_db_filename(db, nullptr);
if (!path) path = "(in-memory)"; if (!path) {
path = "(in-memory)";
}
if (err == SQLITE_BUSY || err == SQLITE_PROTOCOL) { if (err == SQLITE_BUSY || err == SQLITE_PROTOCOL) {
throw SQLiteBusy( throw SQLiteBusy(
err == SQLITE_PROTOCOL err == SQLITE_PROTOCOL
? fmt("SQLite database '%s' is busy (SQLITE_PROTOCOL)", path) ? fmt("SQLite database '%s' is busy (SQLITE_PROTOCOL)", path)
: fmt("SQLite database '%s' is busy", path)); : fmt("SQLite database '%s' is busy", path));
} else } else {
throw SQLiteError("%s: %s (in '%s')", fs.s, sqlite3_errstr(exterr), path); throw
}
SQLiteError("%s: %s (in '%s')", fs.s, sqlite3_errstr(exterr), path);
} }
SQLite::SQLite(const Path& path) { SQLite::SQLite(const Path& path) {
@ -34,8 +38,9 @@ SQLite::SQLite(const Path& path) {
SQLite::~SQLite() { SQLite::~SQLite() {
try { try {
if (db && sqlite3_close(db) != SQLITE_OK) if (db && sqlite3_close(db) != SQLITE_OK) {
throwSQLiteError(db, "closing database"); throwSQLiteError(db, "closing database");
}
} catch (...) { } catch (...) {
ignoreException(); ignoreException();
} }
@ -81,8 +86,9 @@ SQLiteStmt::Use& SQLiteStmt::Use::operator()(const std::string& value,
if (sqlite3_bind_text(stmt, curArg++, value.c_str(), -1, if (sqlite3_bind_text(stmt, curArg++, value.c_str(), -1,
SQLITE_TRANSIENT) != SQLITE_OK) SQLITE_TRANSIENT) != SQLITE_OK)
throwSQLiteError(stmt.db, "binding argument"); throwSQLiteError(stmt.db, "binding argument");
} else } else {
bind(); bind();
}
return *this; return *this;
} }
@ -90,14 +96,16 @@ SQLiteStmt::Use& SQLiteStmt::Use::operator()(int64_t value, bool notNull) {
if (notNull) { if (notNull) {
if (sqlite3_bind_int64(stmt, curArg++, value) != SQLITE_OK) if (sqlite3_bind_int64(stmt, curArg++, value) != SQLITE_OK)
throwSQLiteError(stmt.db, "binding argument"); throwSQLiteError(stmt.db, "binding argument");
} else } else {
bind(); bind();
}
return *this; return *this;
} }
SQLiteStmt::Use& SQLiteStmt::Use::bind() { SQLiteStmt::Use& SQLiteStmt::Use::bind() {
if (sqlite3_bind_null(stmt, curArg++) != SQLITE_OK) if (sqlite3_bind_null(stmt, curArg++) != SQLITE_OK) {
throwSQLiteError(stmt.db, "binding argument"); throwSQLiteError(stmt.db, "binding argument");
}
return *this; return *this;
} }
@ -134,21 +142,24 @@ bool SQLiteStmt::Use::isNull(int col) {
SQLiteTxn::SQLiteTxn(sqlite3* db) { SQLiteTxn::SQLiteTxn(sqlite3* db) {
this->db = db; this->db = db;
if (sqlite3_exec(db, "begin;", 0, 0, 0) != SQLITE_OK) if (sqlite3_exec(db, "begin;", 0, 0, 0) != SQLITE_OK) {
throwSQLiteError(db, "starting transaction"); throwSQLiteError(db, "starting transaction");
}
active = true; active = true;
} }
void SQLiteTxn::commit() { void SQLiteTxn::commit() {
if (sqlite3_exec(db, "commit;", 0, 0, 0) != SQLITE_OK) if (sqlite3_exec(db, "commit;", 0, 0, 0) != SQLITE_OK) {
throwSQLiteError(db, "committing transaction"); throwSQLiteError(db, "committing transaction");
}
active = false; active = false;
} }
SQLiteTxn::~SQLiteTxn() { SQLiteTxn::~SQLiteTxn() {
try { try {
if (active && sqlite3_exec(db, "rollback;", 0, 0, 0) != SQLITE_OK) if (active && sqlite3_exec(db, "rollback;", 0, 0, 0) != SQLITE_OK) {
throwSQLiteError(db, "aborting transaction"); throwSQLiteError(db, "aborting transaction");
}
} catch (...) { } catch (...) {
ignoreException(); ignoreException();
} }

View file

@ -42,7 +42,9 @@ Path Store::toStorePath(const Path& path) const {
Path Store::followLinksToStore(const Path& _path) const { Path Store::followLinksToStore(const Path& _path) const {
Path path = absPath(_path); Path path = absPath(_path);
while (!isInStore(path)) { while (!isInStore(path)) {
if (!isLink(path)) break; if (!isLink(path)) {
break;
}
string target = readLink(path); string target = readLink(path);
path = absPath(target, dirOf(path)); path = absPath(target, dirOf(path));
} }
@ -828,10 +830,11 @@ StoreType getStoreType(const std::string& uri, const std::string& stateDir) {
} else if (uri == "" || uri == "auto") { } else if (uri == "" || uri == "auto") {
if (access(stateDir.c_str(), R_OK | W_OK) == 0) if (access(stateDir.c_str(), R_OK | W_OK) == 0)
return tLocal; return tLocal;
else if (pathExists(settings.nixDaemonSocketFile)) else if (pathExists(settings.nixDaemonSocketFile)) {
return tDaemon; return tDaemon;
else } else {
return tLocal; return tLocal;
}
} else { } else {
return tOther; return tOther;
} }

View file

@ -36,7 +36,9 @@ void setAffinityTo(int cpu) {
int lockToCurrentCPU() { int lockToCurrentCPU() {
#if __linux__ #if __linux__
int cpu = sched_getcpu(); int cpu = sched_getcpu();
if (cpu != -1) setAffinityTo(cpu); if (cpu != -1) {
setAffinityTo(cpu);
}
return cpu; return cpu;
#else #else
return -1; return -1;

View file

@ -16,35 +16,49 @@
namespace nix { namespace nix {
void Hash::init() { void Hash::init() {
if (type == htMD5) if (type == htMD5) {
hashSize = md5HashSize; hashSize = md5HashSize;
else if (type == htSHA1) } else if (type == htSHA1) {
hashSize = sha1HashSize; hashSize = sha1HashSize;
else if (type == htSHA256) } else if (type == htSHA256) {
hashSize = sha256HashSize; hashSize = sha256HashSize;
else if (type == htSHA512) } else if (type == htSHA512) {
hashSize = sha512HashSize; hashSize = sha512HashSize;
else } else {
abort(); abort();
}
assert(hashSize <= maxHashSize); assert(hashSize <= maxHashSize);
memset(hash, 0, maxHashSize); memset(hash, 0, maxHashSize);
} }
bool Hash::operator==(const Hash& h2) const { bool Hash::operator==(const Hash& h2) const {
if (hashSize != h2.hashSize) return false; if (hashSize != h2.hashSize) {
for (unsigned int i = 0; i < hashSize; i++) return false;
if (hash[i] != h2.hash[i]) return false; }
for (unsigned int i = 0; i < hashSize; i++) {
if (hash[i] != h2.hash[i]) {
return false;
}
}
return true; return true;
} }
bool Hash::operator!=(const Hash& h2) const { return !(*this == h2); } bool Hash::operator!=(const Hash& h2) const { return !(*this == h2); }
bool Hash::operator<(const Hash& h) const { bool Hash::operator<(const Hash& h) const {
if (hashSize < h.hashSize) return true; if (hashSize < h.hashSize) {
if (hashSize > h.hashSize) return false; return true;
}
if (hashSize > h.hashSize) {
return false;
}
for (unsigned int i = 0; i < hashSize; i++) { for (unsigned int i = 0; i < hashSize; i++) {
if (hash[i] < h.hash[i]) return true; if (hash[i] < h.hash[i]) {
if (hash[i] > h.hash[i]) return false; return true;
}
if (hash[i] > h.hash[i]) {
return false;
}
} }
return false; return false;
} }
@ -137,9 +151,15 @@ Hash::Hash(const std::string& s, HashType type) : type(type) {
if (!isSRI && size == base16Len()) { if (!isSRI && size == base16Len()) {
auto parseHexDigit = [&](char c) { auto parseHexDigit = [&](char c) {
if (c >= '0' && c <= '9') return c - '0'; if (c >= '0' && c <= '9') {
if (c >= 'A' && c <= 'F') return c - 'A' + 10; return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10; }
if (c >= 'A' && c <= 'F') {
return c - 'A' + 10;
}
if (c >= 'a' && c <= 'f') {
return c - 'a' + 10;
}
throw BadHash("invalid base-16 hash '%s'", s); throw BadHash("invalid base-16 hash '%s'", s);
}; };
@ -292,8 +312,9 @@ HashResult hashPath(HashType ht, const Path& path, PathFilter& filter) {
Hash compressHash(const Hash& hash, unsigned int newSize) { Hash compressHash(const Hash& hash, unsigned int newSize) {
Hash h; Hash h;
h.hashSize = newSize; h.hashSize = newSize;
for (unsigned int i = 0; i < hash.hashSize; ++i) for (unsigned int i = 0; i < hash.hashSize; ++i) {
h.hash[i % newSize] ^= hash.hash[i]; h.hash[i % newSize] ^= hash.hash[i];
}
return h; return h;
} }

View file

@ -102,7 +102,9 @@ void JSONWriter::comma() {
} else { } else {
state->str << ','; state->str << ',';
} }
if (state->indent) indent(); if (state->indent) {
indent();
}
} }
void JSONWriter::indent() { void JSONWriter::indent() {
@ -116,7 +118,9 @@ void JSONList::open() {
JSONList::~JSONList() { JSONList::~JSONList() {
state->depth--; state->depth--;
if (state->indent && !first) indent(); if (state->indent && !first) {
indent();
}
state->str << "]"; state->str << "]";
} }
@ -143,7 +147,9 @@ void JSONObject::open() {
JSONObject::~JSONObject() { JSONObject::~JSONObject() {
if (state) { if (state) {
state->depth--; state->depth--;
if (state->indent && !first) indent(); if (state->indent && !first) {
indent();
}
state->str << "}"; state->str << "}";
} }
} }

View file

@ -211,7 +211,9 @@ Sink& operator<<(Sink& sink, const string& s) {
template <class T> template <class T>
void writeStrings(const T& ss, Sink& sink) { void writeStrings(const T& ss, Sink& sink) {
sink << ss.size(); sink << ss.size();
for (auto& i : ss) sink << i; for (auto& i : ss) {
sink << i;
}
} }
Sink& operator<<(Sink& sink, const Strings& s) { Sink& operator<<(Sink& sink, const Strings& s) {

View file

@ -194,7 +194,9 @@ bool pathExists(const Path& path) {
int res; int res;
struct stat st; struct stat st;
res = lstat(path.c_str(), &st); res = lstat(path.c_str(), &st);
if (!res) return true; if (!res) {
return true;
}
if (errno != ENOENT && errno != ENOTDIR) if (errno != ENOENT && errno != ENOTDIR)
throw SysError(format("getting status of %1%") % path); throw SysError(format("getting status of %1%") % path);
return false; return false;
@ -579,9 +581,9 @@ AutoDelete::AutoDelete(const string& p, bool recursive) : path(p) {
AutoDelete::~AutoDelete() { AutoDelete::~AutoDelete() {
try { try {
if (del) { if (del) {
if (recursive) if (recursive) {
deletePath(path); deletePath(path);
else { } else {
if (remove(path.c_str()) == -1) if (remove(path.c_str()) == -1)
throw SysError(format("cannot unlink '%1%'") % path); throw SysError(format("cannot unlink '%1%'") % path);
} }
@ -1200,7 +1202,9 @@ string base64Decode(const string& s) {
if (!init) { if (!init) {
// FIXME: not thread-safe. // FIXME: not thread-safe.
memset(decode, -1, sizeof(decode)); memset(decode, -1, sizeof(decode));
for (int i = 0; i < 64; i++) decode[(int)base64Chars[i]] = i; for (int i = 0; i < 64; i++) {
decode[(int)base64Chars[i]] = i;
}
init = true; init = true;
} }

View file

@ -13,13 +13,17 @@ XMLWriter::XMLWriter(bool indent, std::ostream& output)
XMLWriter::~XMLWriter() { close(); } XMLWriter::~XMLWriter() { close(); }
void XMLWriter::close() { void XMLWriter::close() {
if (closed) return; if (closed) {
return;
}
while (!pendingElems.empty()) closeElement(); while (!pendingElems.empty()) closeElement();
closed = true; closed = true;
} }
void XMLWriter::indent_(size_t depth) { void XMLWriter::indent_(size_t depth) {
if (!indent) return; if (!indent) {
return;
}
output << string(depth * 2, ' '); output << string(depth * 2, ' ');
} }

View file

@ -379,7 +379,9 @@ static void _main(int argc, char** argv) {
buildPaths(pathsToBuild); buildPaths(pathsToBuild);
if (dryRun) return; if (dryRun) {
return;
}
// Set the environment. // Set the environment.
auto env = getEnv(); auto env = getEnv();
@ -501,7 +503,9 @@ static void _main(int argc, char** argv) {
buildPaths(pathsToBuild); buildPaths(pathsToBuild);
if (dryRun) return; if (dryRun) {
return;
}
for (auto& symlink : resultSymlinks) for (auto& symlink : resultSymlinks)
if (auto store2 = store.dynamic_pointer_cast<LocalFSStore>()) if (auto store2 = store.dynamic_pointer_cast<LocalFSStore>())

View file

@ -18,7 +18,9 @@ static Path channelsList;
// Reads the list of channels. // Reads the list of channels.
static void readChannels() { static void readChannels() {
if (!pathExists(channelsList)) return; if (!pathExists(channelsList)) {
return;
}
auto channelsFile = readFile(channelsList); auto channelsFile = readFile(channelsList);
for (const auto& line : for (const auto& line :

View file

@ -117,9 +117,9 @@ struct TunnelLogger {
state->canSendStderr = false; state->canSendStderr = false;
if (success) if (success) {
to << STDERR_LAST; to << STDERR_LAST;
else { } else {
to << STDERR_ERROR << msg; to << STDERR_ERROR << msg;
if (status != 0) to << status; if (status != 0) to << status;
} }
@ -304,8 +304,10 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
addToStoreFromDump(). */ addToStoreFromDump(). */
ParseSink sink; /* null sink; just parse the NAR */ ParseSink sink; /* null sink; just parse the NAR */
parseDump(sink, savedNAR); parseDump(sink, savedNAR);
} else } else {
parseDump(savedRegular, from); parseDump
}
(savedRegular, from);
logger->startWork(); logger->startWork();
if (!savedRegular.regular) throw Error("regular file expected"); if (!savedRegular.regular) throw Error("regular file expected");
@ -575,7 +577,9 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
try { try {
info = store->queryPathInfo(path); info = store->queryPathInfo(path);
} catch (InvalidPath&) { } catch (InvalidPath&) {
if (GET_PROTOCOL_MINOR(clientVersion) < 17) throw; if (GET_PROTOCOL_MINOR(clientVersion) < 17) {
throw;
}
} }
logger->stopWork(); logger->stopWork();
if (info) { if (info) {
@ -641,14 +645,18 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
from >> info.registrationTime >> info.narSize >> info.ultimate; from >> info.registrationTime >> info.narSize >> info.ultimate;
info.sigs = readStrings<StringSet>(from); info.sigs = readStrings<StringSet>(from);
from >> info.ca >> repair >> dontCheckSigs; from >> info.ca >> repair >> dontCheckSigs;
if (!trusted && dontCheckSigs) dontCheckSigs = false; if (!trusted && dontCheckSigs) {
if (!trusted) info.ultimate = false; dontCheckSigs = false;
}
if (!trusted) {
info.ultimate = false;
}
std::string saved; std::string saved;
std::unique_ptr<Source> source; std::unique_ptr<Source> source;
if (GET_PROTOCOL_MINOR(clientVersion) >= 21) if (GET_PROTOCOL_MINOR(clientVersion) >= 21) {
source = std::make_unique<TunnelSource>(from); source = std::make_unique<TunnelSource>(from);
else { } else {
TeeSink tee(from); TeeSink tee(from);
parseDump(tee, tee.source); parseDump(tee, tee.source);
saved = std::move(*tee.source.data); saved = std::move(*tee.source.data);
@ -758,7 +766,9 @@ static void processConnection(bool trusted, const std::string& userName,
happens, just send the error message and exit. */ happens, just send the error message and exit. */
bool errorAllowed = tunnelLogger->state_.lock()->canSendStderr; bool errorAllowed = tunnelLogger->state_.lock()->canSendStderr;
tunnelLogger->stopWork(false, e.msg(), e.status); tunnelLogger->stopWork(false, e.msg(), e.status);
if (!errorAllowed) throw; if (!errorAllowed) {
throw;
}
} catch (std::bad_alloc& e) { } catch (std::bad_alloc& e) {
tunnelLogger->stopWork(false, "Nix daemon out of memory", 1); tunnelLogger->stopWork(false, "Nix daemon out of memory", 1);
throw; throw;

View file

@ -449,7 +449,9 @@ static void installDerivations(Globals& globals, const Strings& args,
printMissing(*globals.state, newElems); printMissing(*globals.state, newElems);
if (globals.dryRun) return; if (globals.dryRun) {
return;
}
if (createUserEnv(*globals.state, allElems, profile, if (createUserEnv(*globals.state, allElems, profile,
settings.envKeepDerivations, lockToken)) settings.envKeepDerivations, lockToken))
@ -557,7 +559,9 @@ static void upgradeDerivations(Globals& globals, const Strings& args,
printMissing(*globals.state, newElems); printMissing(*globals.state, newElems);
if (globals.dryRun) return; if (globals.dryRun) {
return;
}
if (createUserEnv(*globals.state, newElems, globals.profile, if (createUserEnv(*globals.state, newElems, globals.profile,
settings.envKeepDerivations, lockToken)) settings.envKeepDerivations, lockToken))
@ -654,12 +658,16 @@ static void opSet(Globals& globals, Strings opFlags, Strings opArgs) {
if (drv.queryDrvPath() != "") { if (drv.queryDrvPath() != "") {
PathSet paths = {drv.queryDrvPath()}; PathSet paths = {drv.queryDrvPath()};
printMissing(globals.state->store, paths); printMissing(globals.state->store, paths);
if (globals.dryRun) return; if (globals.dryRun) {
return;
}
globals.state->store->buildPaths( globals.state->store->buildPaths(
paths, globals.state->repair ? bmRepair : bmNormal); paths, globals.state->repair ? bmRepair : bmNormal);
} else { } else {
printMissing(globals.state->store, {drv.queryOutPath()}); printMissing(globals.state->store, {drv.queryOutPath()});
if (globals.dryRun) return; if (globals.dryRun) {
return;
}
globals.state->store->ensurePath(drv.queryOutPath()); globals.state->store->ensurePath(drv.queryOutPath());
} }
@ -694,7 +702,9 @@ static void uninstallDerivations(Globals& globals, Strings& selectors,
if (!found) newElems.push_back(i); if (!found) newElems.push_back(i);
} }
if (globals.dryRun) return; if (globals.dryRun) {
return;
}
if (createUserEnv(*globals.state, newElems, profile, if (createUserEnv(*globals.state, newElems, profile,
settings.envKeepDerivations, lockToken)) settings.envKeepDerivations, lockToken))
@ -1128,7 +1138,9 @@ static void opQuery(Globals& globals, Strings opFlags, Strings opArgs) {
} }
} }
if (!xmlOutput) printTable(table); if (!xmlOutput) {
printTable(table);
}
} }
static void opSwitchProfile(Globals& globals, Strings opFlags, Strings opArgs) { static void opSwitchProfile(Globals& globals, Strings opFlags, Strings opArgs) {
@ -1168,7 +1180,9 @@ static void switchGeneration(Globals& globals, int dstGen) {
LOG(INFO) << "switching from generation " << curGen << " to " << dst.number; LOG(INFO) << "switching from generation " << curGen << " to " << dst.number;
if (globals.dryRun) return; if (globals.dryRun) {
return;
}
switchLink(globals.profile, dst.path); switchLink(globals.profile, dst.path);
} }

View file

@ -147,7 +147,9 @@ static int _main(int argc, char** argv) {
initPlugins(); initPlugins();
if (evalOnly && !wantsReadWrite) settings.readOnlyMode = true; if (evalOnly && !wantsReadWrite) {
settings.readOnlyMode = true;
}
auto store = openStore(); auto store = openStore();
@ -171,8 +173,10 @@ static int _main(int argc, char** argv) {
Expr* e = state->parseStdin(); Expr* e = state->parseStdin();
processExpr(*state, attrPaths, parseOnly, strict, autoArgs, evalOnly, processExpr(*state, attrPaths, parseOnly, strict, autoArgs, evalOnly,
outputKind, xmlOutputSourceLocation, e); outputKind, xmlOutputSourceLocation, e);
} else if (files.empty() && !fromArgs) } else {
files.push_back("./default.nix"); if
}
(files.empty() && !fromArgs) files.push_back("./default.nix");
for (auto& i : files) { for (auto& i : files) {
Expr* e = fromArgs Expr* e = fromArgs

View file

@ -151,7 +151,9 @@ static void opRealise(Strings opFlags, Strings opArgs) {
printMissing(ref<Store>(store), willBuild, willSubstitute, unknown, printMissing(ref<Store>(store), willBuild, willSubstitute, unknown,
downloadSize, narSize); downloadSize, narSize);
if (dryRun) return; if (dryRun) {
return;
}
/* Build all paths at the same time to exploit parallelism. */ /* Build all paths at the same time to exploit parallelism. */
store->buildPaths(PathSet(paths.begin(), paths.end()), buildMode); store->buildPaths(PathSet(paths.begin(), paths.end()), buildMode);
@ -217,7 +219,9 @@ static void opPrintFixedPath(Strings opFlags, Strings opArgs) {
static PathSet maybeUseOutputs(const Path& storePath, bool useOutput, static PathSet maybeUseOutputs(const Path& storePath, bool useOutput,
bool forceRealise) { bool forceRealise) {
if (forceRealise) realisePath(storePath); if (forceRealise) {
realisePath(storePath);
}
if (useOutput && isDerivation(storePath)) { if (useOutput && isDerivation(storePath)) {
Derivation drv = store->derivationFromPath(storePath); Derivation drv = store->derivationFromPath(storePath);
PathSet outputs; PathSet outputs;
@ -334,7 +338,9 @@ static void opQuery(Strings opFlags, Strings opArgs) {
i); i);
} }
if (query == qDefault) query = qOutputs; if (query == qDefault) {
query = qOutputs;
}
RunPager pager; RunPager pager;

View file

@ -40,7 +40,9 @@ struct CmdBuild : MixDryRun, InstallablesCommand {
void run(ref<Store> store) override { void run(ref<Store> store) override {
auto buildables = build(store, dryRun ? DryRun : Build, installables); auto buildables = build(store, dryRun ? DryRun : Build, installables);
if (dryRun) return; if (dryRun) {
return;
}
for (size_t i = 0; i < buildables.size(); ++i) { for (size_t i = 0; i < buildables.size(); ++i) {
auto& b(buildables[i]); auto& b(buildables[i]);

View file

@ -36,7 +36,9 @@ struct CmdDoctor : StoreCommand {
} }
success &= checkStoreProtocol(store->getProtocol()); success &= checkStoreProtocol(store->getProtocol());
if (!success) throw Exit(2); if (!success) {
throw Exit(2);
}
} }
bool checkNixInPath() { bool checkNixInPath() {

View file

@ -22,7 +22,9 @@ SourceExprCommand::SourceExprCommand() {
} }
Value* SourceExprCommand::getSourceExpr(EvalState& state) { Value* SourceExprCommand::getSourceExpr(EvalState& state) {
if (vSourceExpr) return vSourceExpr; if (vSourceExpr) {
return vSourceExpr;
}
auto sToplevel = state.symbols.create("_toplevel"); auto sToplevel = state.symbols.create("_toplevel");
@ -223,7 +225,9 @@ std::shared_ptr<Installable> parseInstallable(SourceExprCommand& cmd,
Buildables build(ref<Store> store, RealiseMode mode, Buildables build(ref<Store> store, RealiseMode mode,
std::vector<std::shared_ptr<Installable>> installables) { std::vector<std::shared_ptr<Installable>> installables) {
if (mode != Build) settings.readOnlyMode = true; if (mode != Build) {
settings.readOnlyMode = true;
}
Buildables buildables; Buildables buildables;
@ -244,8 +248,10 @@ Buildables build(ref<Store> store, RealiseMode mode,
if (mode == DryRun) { if (mode == DryRun) {
printMissing(store, pathsToBuild); printMissing(store, pathsToBuild);
} else if (mode == Build) } else {
store->buildPaths(pathsToBuild); if
}
(mode == Build) store->buildPaths(pathsToBuild);
return buildables; return buildables;
} }

View file

@ -13,7 +13,9 @@ struct RegisterLegacyCommand {
static Commands* commands; static Commands* commands;
RegisterLegacyCommand(const std::string& name, MainFunction fun) { RegisterLegacyCommand(const std::string& name, MainFunction fun) {
if (!commands) commands = new Commands; if (!commands) {
commands = new Commands;
}
(*commands)[name] = fun; (*commands)[name] = fun;
} }
}; };

View file

@ -74,8 +74,10 @@ struct MixLs : virtual Args, MixJSON {
if (json) { if (json) {
JSONPlaceholder jsonRoot(std::cout); JSONPlaceholder jsonRoot(std::cout);
listNar(jsonRoot, accessor, path, recursive); listNar(jsonRoot, accessor, path, recursive);
} else } else {
listText(accessor); listText
}
(accessor);
} }
}; };

View file

@ -155,7 +155,9 @@ static char* completionCallback(char* s, int* match) {
}; };
size_t start = strlen(s); size_t start = strlen(s);
size_t len = 0; size_t len = 0;
while (checkAllHaveSameAt(start + len)) ++len; while (checkAllHaveSameAt(start + len)) {
++len;
}
if (len > 0) { if (len > 0) {
*match = 1; *match = 1;
auto* res = strdup(std::string(*possible.begin(), start, len).c_str()); auto* res = strdup(std::string(*possible.begin(), start, len).c_str());
@ -295,7 +297,9 @@ bool NixRepl::getLine(string& input, const std::string& prompt) {
return true; return true;
} }
if (!s) return false; if (!s) {
return false;
}
input += s; input += s;
input += '\n'; input += '\n';
return true; return true;
@ -384,7 +388,9 @@ static int runProgram(const string& program, const Strings& args) {
bool isVarName(const string& s) { bool isVarName(const string& s) {
if (s.size() == 0) return false; if (s.size() == 0) return false;
char c = s[0]; char c = s[0];
if ((c >= '0' && c <= '9') || c == '-' || c == '\'') return false; if ((c >= '0' && c <= '9') || c == '-' || c == '\'') {
return false;
}
for (auto& i : s) for (auto& i : s)
if (!((i >= 'a' && i <= 'z') || (i >= 'A' && i <= 'Z') || if (!((i >= 'a' && i <= 'z') || (i >= 'A' && i <= 'Z') ||
(i >= '0' && i <= '9') || i == '_' || i == '-' || i == '\'')) (i >= '0' && i <= '9') || i == '_' || i == '-' || i == '\''))
@ -682,8 +688,10 @@ std::ostream& NixRepl::printValue(std::ostream& str, Value& v,
} }
str << "}"; str << "}";
} else } else {
str << "{ ... }"; str
}
<< "{ ... }";
break; break;
} }
@ -694,7 +702,7 @@ std::ostream& NixRepl::printValue(std::ostream& str, Value& v,
seen.insert(&v); seen.insert(&v);
str << "[ "; str << "[ ";
if (maxDepth > 0) if (maxDepth > 0) {
for (unsigned int n = 0; n < v.listSize(); ++n) { for (unsigned int n = 0; n < v.listSize(); ++n) {
if (seen.find(v.listElems()[n]) != seen.end()) if (seen.find(v.listElems()[n]) != seen.end())
str << "«repeated»"; str << "«repeated»";
@ -706,8 +714,10 @@ std::ostream& NixRepl::printValue(std::ostream& str, Value& v,
} }
str << " "; str << " ";
} }
else } else {
str << "... "; str
}
<< "... ";
str << "]"; str << "]";
break; break;