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;
throw;
}
} else if (v.type == tApp)
} else if (v.type == tApp) {
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);
}
}
inline void EvalState::forceAttrs(Value& v) {
forceValue(v);
if (v.type != tAttrs)
if (v.type != tAttrs) {
throwTypeError("value is %1% while a set was expected", v);
}
}
inline void EvalState::forceAttrs(Value& v, const Pos& pos) {
forceValue(v);
if (v.type != tAttrs)
if (v.type != tAttrs) {
throwTypeError("value is %1% while a set was expected, at %2%", v, pos);
}
}
inline void EvalState::forceList(Value& 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) {
forceValue(v);
if (!v.isList())
if (!v.isList()) {
throwTypeError("value is %1% while a list was expected, at %2%", v, pos);
}
}
/* 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)); }
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) {
if (env->type == Env::HasWithExpr) {
if (noEval) return 0;
if (noEval) {
return 0;
}
Value* v = allocValue();
evalAttrs(*env->up, (Expr*)env->values[0], *v);
env->values[0] = v;
@ -566,8 +571,9 @@ inline Value* EvalState::lookupVar(Env* env, const ExprVar& var, bool noEval) {
if (!env->prevWith)
throwUndefinedVarError("undefined variable '%1%' at %2%", var.name,
var.pos);
for (size_t l = env->prevWith; l; --l, env = env->up)
for (size_t l = env->prevWith; l; --l, env = env->up) {
;
}
}
}
@ -601,11 +607,11 @@ Env& EvalState::allocEnv(size_t size) {
void EvalState::mkList(Value& v, size_t size) {
clearValue(v);
if (size == 1)
if (size == 1) {
v.type = tList1;
else if (size == 2)
} else if (size == 2) {
v.type = tList2;
else {
} else {
v.type = tListN;
v.bigList.size = size;
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);
if (j != fileParseCache.end()) e = j->second;
if (!e) e = parseExprFromFile(checkSourcePath(path2));
if (!e) {
e = parseExprFromFile(checkSourcePath(path2));
}
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) {
Value v;
e->eval(*this, env, v);
if (v.type != tBool)
if (v.type != tBool) {
throwTypeError("value is %1% while a Boolean was expected", v);
}
return v.boolean;
}
inline bool EvalState::evalBool(Env& env, Expr* e, const Pos& pos) {
Value 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);
}
return v.boolean;
}
inline void EvalState::evalAttrs(Env& env, Expr* e, Value& v) {
e->eval(*this, env, v);
if (v.type != tAttrs)
if (v.type != tAttrs) {
throwTypeError("value is %1% while a set was expected", v);
}
}
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);
Bindings* newBnds =
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) {
AttrDefs::iterator j = attrs.find(i.name);
if (j != attrs.end()) {
@ -809,10 +822,12 @@ void ExprAttrs::eval(EvalState& state, Env& env, Value& v) {
}
}
else
for (auto& i : attrs)
v.attrs->push_back(
Attr(i.first, i.second.e->maybeThunk(state, env), &i.second.pos));
else {
for
}
(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. */
for (auto& i : dynamicAttrs) {
@ -980,8 +995,10 @@ void EvalState::callPrimOp(Value& fun, Value& arg, Value& v, const Pos& pos) {
Value* vArgs[arity];
auto n = arity - 1;
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;
}
/* And call the primop. */
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(
"attempt to call something which is not a function but %1%, at %2%",
fun, pos);
}
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;
if (!lambda.matchAttrs)
if (!lambda.matchAttrs) {
env2.values[displ++] = &arg;
else {
} else {
forceAttrs(arg, pos);
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++;
if (countCalls) incrFunctionCall(&lambda);
if (countCalls) {
incrFunctionCall(&lambda);
}
/* Evaluate the body. This is conditional on showTrace, because
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++);
}
while (i != v1.attrs->end()) v.attrs->push_back(*i++);
while (j != v2.attrs->end()) v.attrs->push_back(*j++);
while (i != v1.attrs->end()) {
v.attrs->push_back(*i++);
}
while (j != v2.attrs->end()) {
v.attrs->push_back(*j++);
}
state.nrOpUpdateValuesCopied += v.attrs->size();
}
@ -1248,7 +1272,9 @@ void EvalState::concatLists(Value& v, size_t nrLists, Value** lists,
forceList(*lists[n], pos);
auto l = lists[n]->listSize();
len += l;
if (l) nonEmpty = lists[n];
if (l) {
nonEmpty = lists[n];
}
}
if (nonEmpty && len == nonEmpty->listSize()) {
@ -1311,11 +1337,11 @@ void ExprConcatStrings::eval(EvalState& state, Env& env, Value& v) {
firstType == tString);
}
if (firstType == tInt)
if (firstType == tInt) {
mkInt(v, n);
else if (firstType == tFloat)
} else if (firstType == tFloat) {
mkFloat(v, nf);
else if (firstType == tPath) {
} else if (firstType == tPath) {
if (!context.empty())
throwEvalError(
"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);
auto path = canonPath(s.str());
mkPath(v, path.c_str());
} else
mkString(v, s.str(), context);
} else {
mkString
}
(v, s.str(), context);
}
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) {
forceValue(v, pos);
if (v.type != tInt)
if (v.type != tInt) {
throwTypeError("value is %1% while an integer was expected, at %2%", v,
pos);
}
return v.integer;
}
NixFloat EvalState::forceFloat(Value& v, const Pos& pos) {
forceValue(v, pos);
if (v.type == tInt)
if (v.type == tInt) {
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);
}
return v.fpoint;
}
bool EvalState::forceBool(Value& v, const Pos& pos) {
forceValue(v);
if (v.type != tBool)
if (v.type != tBool) {
throwTypeError("value is %1% while a Boolean was expected, at %2%", v, pos);
}
return v.boolean;
}
@ -1391,19 +1422,21 @@ bool EvalState::isFunctor(Value& fun) {
void EvalState::forceFunction(Value& v, const Pos& pos) {
forceValue(v);
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,
pos);
}
}
string EvalState::forceString(Value& v, const Pos& pos) {
forceValue(v, pos);
if (v.type != tString) {
if (pos)
if (pos) {
throwTypeError("value is %1% while a string was expected, at %2%", v,
pos);
else
} else {
throwTypeError("value is %1% while a string was expected", v);
}
}
return string(v.string.s);
}
@ -1437,11 +1470,17 @@ string EvalState::forceStringNoCtx(Value& v, const Pos& pos) {
}
bool EvalState::isDerivation(Value& v) {
if (v.type != tAttrs) return false;
if (v.type != tAttrs) {
return false;
}
Bindings::iterator i = v.attrs->find(sType);
if (i == v.attrs->end()) return false;
if (i == v.attrs->end()) {
return false;
}
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;
}
@ -1556,14 +1595,22 @@ bool EvalState::eqValues(Value& v1, Value& v2) {
/* !!! Hack to support some old broken code that relies on pointer
equality tests between sets. (Specifically, builderDefs calls
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
if (v1.type == tInt && v2.type == tFloat) return v1.integer == v2.fpoint;
if (v1.type == tFloat && v2.type == tInt) return v1.fpoint == v2.integer;
if (v1.type == tInt && v2.type == tFloat) {
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.
if (v1.type != v2.type) return false;
if (v1.type != v2.type) {
return false;
}
switch (v1.type) {
case tInt:
@ -1584,9 +1631,14 @@ bool EvalState::eqValues(Value& v1, Value& v2) {
case tList1:
case tList2:
case tListN:
if (v1.listSize() != v2.listSize()) return false;
for (size_t n = 0; n < v1.listSize(); ++n)
if (!eqValues(*v1.listElems()[n], *v2.listElems()[n])) return false;
if (v1.listSize() != v2.listSize()) {
return false;
}
for (size_t n = 0; n < v1.listSize(); ++n) {
if (!eqValues(*v1.listElems()[n], *v2.listElems()[n])) {
return false;
}
}
return true;
case tAttrs: {
@ -1595,17 +1647,21 @@ bool EvalState::eqValues(Value& v1, Value& v2) {
if (isDerivation(v1) && isDerivation(v2)) {
Bindings::iterator i = v1.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);
}
}
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. */
Bindings::iterator i, j;
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;
}
return true;
}

View file

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

View file

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

View file

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

View file

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

View file

@ -23,13 +23,25 @@ MakeError(EvalError, Error) MakeError(ParseError, Error)
: file(file), line(line), column(column){};
operator bool() const { return line != 0; }
bool operator<(const Pos& p2) const {
if (!line) return p2.line;
if (!p2.line) return false;
if (!line) {
return p2.line;
}
if (!p2.line) {
return false;
}
int d = ((string)file).compare((string)p2.file);
if (d < 0) return true;
if (d > 0) return false;
if (line < p2.line) return true;
if (line > p2.line) return false;
if (d < 0) {
return true;
}
if (d > 0) {
return false;
}
if (line < p2.line) {
return true;
}
if (line > p2.line) {
return false;
}
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);
} else {
state.forceAttrs(*args[0]);
if (args[0]->attrs->empty())
if (args[0]->attrs->empty()) {
state.evalFile(realPath, v);
else {
} else {
Env* env = &state.allocEnv(args[0]->attrs->size());
env->up = &state.baseEnv;
@ -346,8 +346,12 @@ static void prim_isPath(EvalState& state, const Pos& pos, Value** args,
struct CompareValues {
bool operator()(const Value* v1, const Value* v2) const {
if (v1->type == tFloat && v2->type == tInt) return v1->fpoint < v2->integer;
if (v1->type == tInt && v2->type == tFloat) return v1->integer < v2->fpoint;
if (v1->type == tFloat && v2->type == tInt) {
return v1->fpoint < v2->integer;
}
if (v1->type == tInt && v2->type == tFloat) {
return v1->integer < v2->fpoint;
}
if (v1->type != v2->type)
throw EvalError(format("cannot compare %1% with %2%") % showType(*v1) %
showType(*v2));
@ -562,8 +566,9 @@ static void prim_derivationStrict(EvalState& state, const Pos& pos,
/* Check whether null attributes should be ignored. */
bool ignoreNulls = false;
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);
}
/* Build the derivation expression by processing the attributes. */
Derivation drv;
@ -890,10 +895,11 @@ static void prim_dirOf(EvalState& state, const Pos& pos, Value** args,
Value& v) {
PathSet context;
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());
else
} else {
mkString(v, dir, context);
}
}
/* 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());
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) {
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;
}
}
/* 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);
state.forceAttrs(*args[1], pos);
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);
else
} else {
state.mkPos(v, i->pos);
}
}
/* 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) {
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]);
state.forceAttrs(v2, pos);
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);
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
@ -1454,8 +1470,9 @@ static void prim_tail(EvalState& state, const Pos& pos, Value** args,
if (args[0]->listSize() == 0)
throw Error(format("'tail' called on an empty list, at %1%") % pos);
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];
}
}
/* 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());
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],
*args[1]->listElems()[n]);
}
}
/* 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) {
Value res;
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];
else
} else {
same = false;
}
}
if (same)
if (same) {
v = *args[1];
else {
} else {
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) {
bool res = false;
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])) {
res = true;
break;
}
}
mkBool(v, res);
}
@ -1610,8 +1632,9 @@ static void prim_sort(EvalState& state, const Pos& pos, Value** args,
auto comparator = [&](Value* a, Value* b) {
/* Optimization: if the comparator is lessThan, bypass
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);
}
Value vTmp1, vTmp2;
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) {
state.forceValue(*args[0], 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,
state.forceFloat(*args[0], pos) + state.forceFloat(*args[1], pos));
else
} else {
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) {
state.forceValue(*args[0], 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,
state.forceFloat(*args[0], pos) - state.forceFloat(*args[1], pos));
else
} else {
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) {
state.forceValue(*args[0], 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,
state.forceFloat(*args[0], pos) * state.forceFloat(*args[1], pos));
else
} else {
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) {
@ -1937,10 +1963,12 @@ static void prim_concatStringSep(EvalState& state, const Pos& pos, Value** args,
bool first = true;
for (unsigned int n = 0; n < args[1]->listSize(); ++n) {
if (first)
if (first) {
first = false;
else
res += sep;
} else {
res
}
+= sep;
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())
throw EvalError(format("'url' argument required, at %1%") % pos);
} else
request.uri = state.forceStringNoCtx(*args[0], pos);
} else {
request
}
.uri = state.forceStringNoCtx(*args[0], pos);
state.checkURI(request.uri);

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -59,16 +59,18 @@ N getIntArg(const string& opt, Strings::iterator& i,
if (allowUnit && !s.empty()) {
char u = std::toupper(*s.rbegin());
if (std::isalpha(u)) {
if (u == 'K')
if (u == 'K') {
multiplier = 1ULL << 10;
else if (u == 'M')
} else if (u == 'M') {
multiplier = 1ULL << 20;
else if (u == 'G')
} else if (u == 'G') {
multiplier = 1ULL << 30;
else if (u == 'T')
} else if (u == 'T') {
multiplier = 1ULL << 40;
else
throw UsageError(format("invalid unit specifier '%1%'") % u);
} else {
throw
}
UsageError(format("invalid unit specifier '%1%'") % u);
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());
if (result == ecFailed || result == ecNoSubstituters ||
result == ecIncompleteClosure)
result == ecIncompleteClosure) {
++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 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
build the dependencies of this derivation, but after that, we
can still use the substitutes for this derivation itself. */
if (nrIncompleteClosure > 0) retrySubstitution = true;
if (nrIncompleteClosure > 0) {
retrySubstitution = true;
}
nrFailed = nrNoSubstituters = nrIncompleteClosure = 0;
@ -1659,7 +1666,9 @@ MakeError(NotDeterministic, BuildError)
}
HookReply DerivationGoal::tryBuildHook() {
if (!worker.tryBuildHook || !useDerivation) return rpDecline;
if (!worker.tryBuildHook || !useDerivation) {
return rpDecline;
}
if (!worker.hook) worker.hook = std::make_unique<HookInstance>();
@ -2231,7 +2240,9 @@ void DerivationGoal::startBuilder() {
us.
*/
if (!fixedOutput) privateNetwork = true;
if (!fixedOutput) {
privateNetwork = true;
}
userNamespaceSync.create();
@ -3117,7 +3128,9 @@ void DerivationGoal::registerOutputs() {
bool allValid = true;
for (auto& i : drv->outputs)
if (!worker.store.isValidPath(i.second.path)) allValid = false;
if (allValid) return;
if (allValid) {
return;
}
}
std::map<std::string, ValidPathInfo> infos;
@ -3345,7 +3358,9 @@ void DerivationGoal::registerOutputs() {
infos[i.first] = info;
}
if (buildMode == bmCheck) return;
if (buildMode == bmCheck) {
return;
}
/* Apply output checks. */
checkOutputs(infos);
@ -4095,9 +4110,10 @@ GoalPtr Worker::makeDerivationGoal(const Path& path,
std::make_shared<DerivationGoal>(path, wantedOutputs, *this, buildMode);
derivationGoals[path] = goal;
wakeUp(goal);
} else
} else {
(dynamic_cast<DerivationGoal*>(goal.get()))
->addWantedOutputs(wantedOutputs);
}
return goal;
}
@ -4167,7 +4183,9 @@ void Worker::childStarted(GoalPtr goal, const set<int>& fds, bool inBuildSlot,
child.inBuildSlot = inBuildSlot;
child.respectTimeouts = respectTimeouts;
children.emplace_back(child);
if (inBuildSlot) nrLocalBuilds++;
if (inBuildSlot) {
nrLocalBuilds++;
}
}
void Worker::childTerminated(Goal* goal, bool wakeSleepers) {
@ -4413,14 +4431,22 @@ unsigned int Worker::exitStatus() {
*/
unsigned int mask = 0;
bool buildFailure = permanentFailure || timedOut || hashMismatch;
if (buildFailure) mask |= 0x04; // 100
if (timedOut) mask |= 0x01; // 101
if (hashMismatch) mask |= 0x02; // 102
if (buildFailure) {
mask |= 0x04; // 100
}
if (timedOut) {
mask |= 0x01; // 101
}
if (hashMismatch) {
mask |= 0x02; // 102
}
if (checkMismatch) {
mask |= 0x08; // 104
}
if (mask) mask |= 0x60;
if (mask) {
mask |= 0x60;
}
return mask ? mask : 1;
}
@ -4430,9 +4456,9 @@ bool Worker::pathContentsGood(const Path& path) {
LOG(INFO) << "checking path '" << path << "'...";
auto info = store.queryPathInfo(path);
bool res;
if (!pathExists(path))
if (!pathExists(path)) {
res = false;
else {
} else {
HashResult current = hashPath(info->narHash.type, path);
Hash nullHash(htSHA256);
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) {
res += '"';
for (const char* i = s.c_str(); *i; i++)
for (const char* i = s.c_str(); *i; i++) {
if (*i == '\"' || *i == '\\') {
res += "\\";
res += *i;
} else if (*i == '\n')
} else if (*i == '\n') {
res += "\\n";
else if (*i == '\r')
} else if (*i == '\r') {
res += "\\r";
else if (*i == '\t')
} else if (*i == '\t') {
res += "\\t";
else
} else {
res += *i;
res += '"';
}
res += '"';
}
}
template <class ForwardIterator>
@ -205,10 +207,11 @@ static void printStrings(string& res, ForwardIterator i, ForwardIterator j) {
res += '[';
bool first = true;
for (; i != j; ++i) {
if (first)
if (first) {
first = false;
else
} else {
res += ',';
}
printString(res, *i);
}
res += ']';

View file

@ -108,10 +108,14 @@ struct CurlDownloader : public Downloader {
~DownloadItem() {
if (req) {
if (active) curl_multi_remove_handle(downloader.curlm, req);
if (active) {
curl_multi_remove_handle(downloader.curlm, req);
}
curl_easy_cleanup(req);
}
if (requestHeaders) curl_slist_free_all(requestHeaders);
if (requestHeaders) {
curl_slist_free_all(requestHeaders);
}
try {
if (!done)
fail(DownloadError(
@ -242,7 +246,9 @@ struct CurlDownloader : public Downloader {
}
void init() {
if (!req) req = curl_easy_init();
if (!req) {
req = curl_easy_init();
}
curl_easy_reset(req);
@ -316,8 +322,9 @@ struct CurlDownloader : public Downloader {
settings.netrcFile.get().c_str());
curl_easy_setopt(req, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
if (writtenToSink)
if (writtenToSink) {
curl_easy_setopt(req, CURLOPT_RESUME_FROM_LARGE, writtenToSink);
}
result.data = std::make_shared<std::string>();
result.bodySize = 0;
@ -505,7 +512,9 @@ struct CurlDownloader : public Downloader {
workerThread.join();
if (curlm) curl_multi_cleanup(curlm);
if (curlm) {
curl_multi_cleanup(curlm);
}
}
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
recursing into derivations and outputs. */
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 ||
options.action == GCOptions::gcDeleteSpecific;
if (state.shouldDelete) deletePath(reservedPath);
if (state.shouldDelete) {
deletePath(reservedPath);
}
/* Acquire the global GC root. This prevents
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. */
if (state.shouldDelete) {
if (pathExists(trashDir)) deleteGarbage(state, trashDir);
if (pathExists(trashDir)) {
deleteGarbage(state, trashDir);
}
try {
createDirs(trashDir);
} catch (SysError& e) {

View file

@ -77,8 +77,9 @@ class HttpBinaryCacheStore : public BinaryCacheStore {
} catch (DownloadError& e) {
/* S3 buckets return 403 if a file doesn't exist and the
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;
}
maybeDisable();
throw;
}

View file

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

View file

@ -157,19 +157,17 @@ LocalStore::LocalStore(const Params& params)
/* Check the current database schema and if necessary do an
upgrade. */
int curSchema = getSchema();
if (curSchema > nixSchemaVersion)
if (curSchema > nixSchemaVersion) {
throw Error(
format(
"current Nix store schema is version %1%, but I only support %2%") %
curSchema % nixSchemaVersion);
else if (curSchema == 0) { /* new store */
} else if (curSchema == 0) { /* new store */
curSchema = nixSchemaVersion;
openDB(*state, true);
writeFile(schemaPath, (format("%1%") % nixSchemaVersion).str());
}
else if (curSchema < nixSchemaVersion) {
} else if (curSchema < nixSchemaVersion) {
if (curSchema < 5)
throw Error(
"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());
lockFile(globalLock.get(), ltRead, true);
}
else
} else {
openDB(*state, false);
}
/* Prepare SQL statements. */
state->stmtRegisterValidPath.create(
@ -325,8 +322,9 @@ void LocalStore::openDB(State& state, bool create) {
SetDllDirectoryW(L"");
#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");
}
db.exec("pragma foreign_keys = 1");
@ -347,8 +345,9 @@ void LocalStore::openDB(State& state, bool create) {
{
SQLiteStmt stmt;
stmt.create(db, "pragma main.journal_mode;");
if (sqlite3_step(stmt) != SQLITE_ROW)
if (sqlite3_step(stmt) != SQLITE_ROW) {
throwSQLiteError(db, "querying journal mode");
}
prevMode = string((const char*)sqlite3_column_text(stmt, 0));
}
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
DB transaction is rolled back, so the path validity
registration above is undone. */
if (checkOutputs) checkDerivationOutputs(info.path, drv);
if (checkOutputs) {
checkDerivationOutputs(info.path, drv);
}
for (auto& i : drv.outputs) {
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) {
StringSource source(dump);
restorePath(realPath, source);
} else
} else {
writeFile(realPath, dump);
}
canonicalisePathMetaData(realPath, -1);
@ -1059,8 +1061,9 @@ Path LocalStore::addToStoreFromDump(const string& dump, const string& name,
if (recursive) {
hash.first = hashAlgo == htSHA256 ? h : hashString(htSHA256, dump);
hash.second = dump.size();
} else
} else {
hash = hashPath(htSHA256, realPath);
}
optimisePath(realPath); // FIXME: combine with hashPath()
@ -1297,14 +1300,16 @@ void LocalStore::verifyPath(const Path& path, const PathSet& store,
} else {
LOG(ERROR) << "path '" << path
<< "' disappeared, but it still has valid referrers!";
if (repair) try {
if (repair) {
try {
repairPath(path);
} catch (Error& e) {
LOG(WARNING) << e.msg();
errors = true;
}
else
} else {
errors = true;
}
}
return;

View file

@ -206,7 +206,9 @@ retry:
the store itself (we don't want or need to mess with its
permissions). */
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
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 isBase32[256];
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)
isBase32[(unsigned char)base32Chars[i]] = true;
initialised = true;

View file

@ -33,7 +33,9 @@ Path readStorePath(Store& store, Source& from) {
template <class T>
T readStorePaths(Store& store, Source& from) {
T paths = readStrings<T>(from);
for (auto& i : paths) store.assertStorePath(i);
for (auto& i : paths) {
store.assertStorePath(i);
}
return paths;
}
@ -600,10 +602,11 @@ void RemoteStore::queryMissing(const PathSet& targets, PathSet& willBuild,
unsigned long long& narSize) {
{
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
// to prevent a deadlock.
goto fallback;
}
conn->to << wopQueryMissing << targets;
conn.processStderr();
willBuild = readStorePaths<PathSet>(*this, conn->from);

View file

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

View file

@ -42,7 +42,9 @@ Path Store::toStorePath(const Path& path) const {
Path Store::followLinksToStore(const Path& _path) const {
Path path = absPath(_path);
while (!isInStore(path)) {
if (!isLink(path)) break;
if (!isLink(path)) {
break;
}
string target = readLink(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") {
if (access(stateDir.c_str(), R_OK | W_OK) == 0)
return tLocal;
else if (pathExists(settings.nixDaemonSocketFile))
else if (pathExists(settings.nixDaemonSocketFile)) {
return tDaemon;
else
} else {
return tLocal;
}
} else {
return tOther;
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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