refactor(3p/nix): Apply clang-tidy's readability-* fixes

This applies the readability fixes listed here:

https://clang.llvm.org/extra/clang-tidy/checks/list.html
This commit is contained in:
Vincent Ambo 2020-05-20 22:27:37 +01:00
parent d331d3a0b5
commit 689ef502f5
78 changed files with 863 additions and 792 deletions

View file

@ -40,7 +40,7 @@ static AutoCloseFD openSlotLock(const Machine& m, unsigned long long slot) {
static bool allSupportedLocally(const std::set<std::string>& requiredFeatures) { static bool allSupportedLocally(const std::set<std::string>& requiredFeatures) {
for (auto& feature : requiredFeatures) { for (auto& feature : requiredFeatures) {
if (!settings.systemFeatures.get().count(feature)) { if (settings.systemFeatures.get().count(feature) == 0u) {
return false; return false;
} }
} }
@ -60,7 +60,7 @@ static int _main(int argc, char* argv[]) {
FdSource source(STDIN_FILENO); FdSource source(STDIN_FILENO);
/* Read the parent's settings. */ /* Read the parent's settings. */
while (readInt(source)) { while (readInt(source) != 0u) {
auto name = readString(source); auto name = readString(source);
auto value = readString(source); auto value = readString(source);
settings.set(name, value); settings.set(name, value);
@ -106,7 +106,7 @@ static int _main(int argc, char* argv[]) {
auto requiredFeatures = readStrings<std::set<std::string>>(source); auto requiredFeatures = readStrings<std::set<std::string>>(source);
auto canBuildLocally = auto canBuildLocally =
amWilling && (amWilling != 0u) &&
(neededSystem == settings.thisSystem || (neededSystem == settings.thisSystem ||
settings.extraPlatforms.get().count(neededSystem) > 0) && settings.extraPlatforms.get().count(neededSystem) > 0) &&
allSupportedLocally(requiredFeatures); allSupportedLocally(requiredFeatures);
@ -196,7 +196,7 @@ static int _main(int argc, char* argv[]) {
if (hasPrefix(bestMachine->storeUri, "ssh://")) { if (hasPrefix(bestMachine->storeUri, "ssh://")) {
storeParams["max-connections"] = "1"; storeParams["max-connections"] = "1";
storeParams["log-fd"] = "4"; storeParams["log-fd"] = "4";
if (bestMachine->sshKey != "") { if (!bestMachine->sshKey.empty()) {
storeParams["ssh-key"] = bestMachine->sshKey; storeParams["ssh-key"] = bestMachine->sshKey;
} }
} }

View file

@ -53,7 +53,8 @@ Path lookupFileArg(EvalState& state, string s) {
CachedDownloadRequest request(s); CachedDownloadRequest request(s);
request.unpack = true; request.unpack = true;
return getDownloader()->downloadCached(state.store, request).path; return getDownloader()->downloadCached(state.store, request).path;
} else if (s.size() > 2 && s.at(0) == '<' && s.at(s.size() - 1) == '>') { }
if (s.size() > 2 && s.at(0) == '<' && s.at(s.size() - 1) == '>') {
Path p = s.substr(1, s.size() - 2); Path p = s.substr(1, s.size() - 2);
return state.findFile(p); return state.findFile(p);
} else { } else {

View file

@ -37,7 +37,7 @@ static char* dupString(const char* s) {
#else #else
t = strdup(s); t = strdup(s);
#endif #endif
if (!t) { if (t == nullptr) {
throw std::bad_alloc(); throw std::bad_alloc();
} }
return t; return t;
@ -62,7 +62,7 @@ static void printValue(std::ostream& str, std::set<const Value*>& active,
break; break;
case tString: case tString:
str << "\""; str << "\"";
for (const char* i = v.string.s; *i; i++) { for (const char* i = v.string.s; *i != 0; i++) {
if (*i == '\"' || *i == '\\') { if (*i == '\"' || *i == '\\') {
str << "\\" << *i; str << "\\" << *i;
} else if (*i == '\n') { } else if (*i == '\n') {
@ -151,7 +151,7 @@ string showType(const Value& v) {
case tBool: case tBool:
return "a boolean"; return "a boolean";
case tString: case tString:
return v.string.context ? "a string with context" : "a string"; return v.string.context != nullptr ? "a string with context" : "a string";
case tPath: case tPath:
return "a path"; return "a path";
case tNull: case tNull:
@ -194,12 +194,11 @@ static void* oomHandler(size_t requested) {
static Symbol getName(const AttrName& name, EvalState& state, Env& env) { static Symbol getName(const AttrName& name, EvalState& state, Env& env) {
if (name.symbol.set()) { if (name.symbol.set()) {
return name.symbol; return name.symbol;
} else {
Value nameValue;
name.expr->eval(state, env, nameValue);
state.forceStringNoCtx(nameValue);
return state.symbols.create(nameValue.string.s);
} }
Value nameValue;
name.expr->eval(state, env, nameValue);
state.forceStringNoCtx(nameValue);
return state.symbols.create(nameValue.string.s);
} }
static bool gcInitialised = false; static bool gcInitialised = false;
@ -233,7 +232,7 @@ void initGC() {
that GC_expand_hp() causes a lot of virtual, but not physical that GC_expand_hp() causes a lot of virtual, but not physical
(resident) memory to be allocated. This might be a problem on (resident) memory to be allocated. This might be a problem on
systems that don't overcommit. */ systems that don't overcommit. */
if (!getenv("GC_INITIAL_HEAP_SIZE")) { if (getenv("GC_INITIAL_HEAP_SIZE") == nullptr) {
size_t size = 32 * 1024 * 1024; size_t size = 32 * 1024 * 1024;
#if HAVE_SYSCONF && defined(_SC_PAGESIZE) && defined(_SC_PHYS_PAGES) #if HAVE_SYSCONF && defined(_SC_PAGESIZE) && defined(_SC_PHYS_PAGES)
size_t maxSize = 384 * 1024 * 1024; size_t maxSize = 384 * 1024 * 1024;
@ -436,7 +435,7 @@ void EvalState::checkURI(const std::string& uri) {
'https://' as prefixes for any http/https URI. */ 'https://' as prefixes for any http/https URI. */
for (auto& prefix : evalSettings.allowedUris.get()) { for (auto& prefix : evalSettings.allowedUris.get()) {
if (uri == prefix || if (uri == prefix ||
(uri.size() > prefix.size() && prefix.size() > 0 && (uri.size() > prefix.size() && !prefix.empty() &&
hasPrefix(uri, prefix) && hasPrefix(uri, prefix) &&
(prefix[prefix.size() - 1] == '/' || uri[prefix.size()] == '/'))) { (prefix[prefix.size() - 1] == '/' || uri[prefix.size()] == '/'))) {
return; return;
@ -583,7 +582,7 @@ 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 != 0u; --l, env = env->up) {
; ;
} }
@ -603,16 +602,16 @@ inline Value* EvalState::lookupVar(Env* env, const ExprVar& var, bool noEval) {
} }
Bindings::iterator j = env->values[0]->attrs->find(var.name); Bindings::iterator j = env->values[0]->attrs->find(var.name);
if (j != env->values[0]->attrs->end()) { if (j != env->values[0]->attrs->end()) {
if (countCalls && j->pos) { if (countCalls && (j->pos != nullptr)) {
attrSelects[*j->pos]++; attrSelects[*j->pos]++;
} }
return j->value; return j->value;
} }
if (!env->prevWith) { if (env->prevWith == 0u) {
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 != 0u; --l, env = env->up) {
; ;
} }
} }
@ -657,7 +656,7 @@ void EvalState::mkList(Value& v, size_t size) {
v.type = tListN; v.type = tListN;
v.bigList.size = size; v.bigList.size = size;
v.bigList.elems = v.bigList.elems =
size ? (Value**)allocBytes(size * sizeof(Value*)) : nullptr; size != 0u ? (Value**)allocBytes(size * sizeof(Value*)) : nullptr;
} }
nrListElems += size; nrListElems += size;
} }
@ -674,7 +673,7 @@ static inline void mkThunk(Value& v, Env& env, Expr* expr) {
void EvalState::mkThunk_(Value& v, Expr* expr) { mkThunk(v, baseEnv, expr); } void EvalState::mkThunk_(Value& v, Expr* expr) { mkThunk(v, baseEnv, expr); }
void EvalState::mkPos(Value& v, Pos* pos) { void EvalState::mkPos(Value& v, Pos* pos) {
if (pos && pos->file.set()) { if ((pos != nullptr) && pos->file.set()) {
mkAttrs(v, 3); mkAttrs(v, 3);
mkString(*allocAttr(v, sFile), pos->file); mkString(*allocAttr(v, sFile), pos->file);
mkInt(*allocAttr(v, sLine), pos->line); mkInt(*allocAttr(v, sLine), pos->line);
@ -701,7 +700,7 @@ Value* ExprVar::maybeThunk(EvalState& state, Env& env) {
Value* v = state.lookupVar(&env, *this, true); Value* v = state.lookupVar(&env, *this, true);
/* The value might not be initialised in the environment yet. /* The value might not be initialised in the environment yet.
In that case, ignore it. */ In that case, ignore it. */
if (v) { if (v != nullptr) {
nrAvoided++; nrAvoided++;
return v; return v;
} }
@ -751,7 +750,7 @@ void EvalState::evalFile(const Path& path_, Value& v) {
e = j->second; e = j->second;
} }
if (!e) { if (e == nullptr) {
e = parseExprFromFile(checkSourcePath(path2)); e = parseExprFromFile(checkSourcePath(path2));
} }
@ -966,7 +965,7 @@ void ExprSelect::eval(EvalState& state, Env& env, Value& v) {
nrLookups++; nrLookups++;
Bindings::iterator j; Bindings::iterator j;
Symbol name = getName(i, state, env); Symbol name = getName(i, state, env);
if (def) { if (def != nullptr) {
state.forceValue(*vAttrs, pos); state.forceValue(*vAttrs, pos);
if (vAttrs->type != tAttrs || if (vAttrs->type != tAttrs ||
(j = vAttrs->attrs->find(name)) == vAttrs->attrs->end()) { (j = vAttrs->attrs->find(name)) == vAttrs->attrs->end()) {
@ -981,7 +980,7 @@ void ExprSelect::eval(EvalState& state, Env& env, Value& v) {
} }
vAttrs = j->value; vAttrs = j->value;
pos2 = j->pos; pos2 = j->pos;
if (state.countCalls && pos2) { if (state.countCalls && (pos2 != nullptr)) {
state.attrSelects[*pos2]++; state.attrSelects[*pos2]++;
} }
} }
@ -989,7 +988,7 @@ void ExprSelect::eval(EvalState& state, Env& env, Value& v) {
state.forceValue(*vAttrs, (pos2 != nullptr ? *pos2 : this->pos)); state.forceValue(*vAttrs, (pos2 != nullptr ? *pos2 : this->pos));
} catch (Error& e) { } catch (Error& e) {
if (pos2 && pos2->file != state.sDerivationNix) { if ((pos2 != nullptr) && pos2->file != state.sDerivationNix) {
addErrorPrefix(e, "while evaluating the attribute '%1%' at %2%:\n", addErrorPrefix(e, "while evaluating the attribute '%1%' at %2%:\n",
showAttrPath(state, env, attrPath), *pos2); showAttrPath(state, env, attrPath), *pos2);
} }
@ -1013,9 +1012,8 @@ void ExprOpHasAttr::eval(EvalState& state, Env& env, Value& v) {
(j = vAttrs->attrs->find(name)) == vAttrs->attrs->end()) { (j = vAttrs->attrs->find(name)) == vAttrs->attrs->end()) {
mkBool(v, false); mkBool(v, false);
return; return;
} else {
vAttrs = j->value;
} }
vAttrs = j->value;
} }
mkBool(v, true); mkBool(v, true);
@ -1133,7 +1131,7 @@ void EvalState::callFunction(Value& fun, Value& arg, Value& v, const Pos& pos) {
for (auto& i : lambda.formals->formals) { for (auto& i : lambda.formals->formals) {
Bindings::iterator j = arg.attrs->find(i.name); Bindings::iterator j = arg.attrs->find(i.name);
if (j == arg.attrs->end()) { if (j == arg.attrs->end()) {
if (!i.def) { if (i.def == nullptr) {
throwTypeError("%1% called without required argument '%2%', at %3%", throwTypeError("%1% called without required argument '%2%', at %3%",
lambda, i.name, pos); lambda, i.name, pos);
} }
@ -1209,7 +1207,7 @@ void EvalState::autoCallFunction(Bindings& args, Value& fun, Value& res) {
Bindings::iterator j = args.find(i.name); Bindings::iterator j = args.find(i.name);
if (j != args.end()) { if (j != args.end()) {
actualArgs->attrs->push_back(*j); actualArgs->attrs->push_back(*j);
} else if (!i.def) { } else if (i.def == nullptr) {
throwTypeError( throwTypeError(
"cannot auto-call a function that has an argument without a default " "cannot auto-call a function that has an argument without a default "
"value ('%1%')", "value ('%1%')",
@ -1278,17 +1276,18 @@ void ExprOpImpl::eval(EvalState& state, Env& env, Value& v) {
} }
void ExprOpUpdate::eval(EvalState& state, Env& env, Value& v) { void ExprOpUpdate::eval(EvalState& state, Env& env, Value& v) {
Value v1, v2; Value v1;
Value v2;
state.evalAttrs(env, e1, v1); state.evalAttrs(env, e1, v1);
state.evalAttrs(env, e2, v2); state.evalAttrs(env, e2, v2);
state.nrOpUpdates++; state.nrOpUpdates++;
if (v1.attrs->size() == 0) { if (v1.attrs->empty()) {
v = v2; v = v2;
return; return;
} }
if (v2.attrs->size() == 0) { if (v2.attrs->empty()) {
v = v1; v = v1;
return; return;
} }
@ -1341,12 +1340,12 @@ 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) { if (l != 0u) {
nonEmpty = lists[n]; nonEmpty = lists[n];
} }
} }
if (nonEmpty && len == nonEmpty->listSize()) { if ((nonEmpty != nullptr) && len == nonEmpty->listSize()) {
v = *nonEmpty; v = *nonEmpty;
return; return;
} }
@ -1355,7 +1354,7 @@ void EvalState::concatLists(Value& v, size_t nrLists, Value** lists,
auto out = v.listElems(); auto out = v.listElems();
for (size_t n = 0, pos = 0; n < nrLists; ++n) { for (size_t n = 0, pos = 0; n < nrLists; ++n) {
auto l = lists[n]->listSize(); auto l = lists[n]->listSize();
if (l) { if (l != 0u) {
memcpy(out + pos, lists[n]->listElems(), l * sizeof(Value*)); memcpy(out + pos, lists[n]->listElems(), l * sizeof(Value*));
} }
pos += l; pos += l;
@ -1479,7 +1478,8 @@ 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) { }
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;
@ -1520,8 +1520,8 @@ string EvalState::forceString(Value& v, const Pos& pos) {
} }
void copyContext(const Value& v, PathSet& context) { void copyContext(const Value& v, PathSet& context) {
if (v.string.context) { if (v.string.context != nullptr) {
for (const char** p = v.string.context; *p; ++p) { for (const char** p = v.string.context; *p != nullptr; ++p) {
context.insert(*p); context.insert(*p);
} }
} }
@ -1535,7 +1535,7 @@ string EvalState::forceString(Value& v, PathSet& context, const Pos& pos) {
string EvalState::forceStringNoCtx(Value& v, const Pos& pos) { string EvalState::forceStringNoCtx(Value& v, const Pos& pos) {
string s = forceString(v, pos); string s = forceString(v, pos);
if (v.string.context) { if (v.string.context != nullptr) {
if (pos) { if (pos) {
throwEvalError( throwEvalError(
"the string '%1%' is not allowed to refer to a store path (such as " "the string '%1%' is not allowed to refer to a store path (such as "
@ -1657,7 +1657,7 @@ string EvalState::copyPathToStore(PathSet& context, const Path& path) {
} }
Path dstPath; Path dstPath;
if (srcToStore[path] != "") { if (!srcToStore[path].empty()) {
dstPath = srcToStore[path]; dstPath = srcToStore[path];
} else { } else {
dstPath = dstPath =
@ -1678,7 +1678,7 @@ string EvalState::copyPathToStore(PathSet& context, const Path& path) {
Path EvalState::coerceToPath(const Pos& pos, Value& v, PathSet& context) { Path EvalState::coerceToPath(const Pos& pos, Value& v, PathSet& context) {
string path = coerceToString(pos, v, context, false, false); string path = coerceToString(pos, v, context, false, false);
if (path == "" || path[0] != '/') { if (path.empty() || path[0] != '/') {
throwEvalError("string '%1%' doesn't represent an absolute path, at %2%", throwEvalError("string '%1%' doesn't represent an absolute path, at %2%",
path, pos); path, pos);
} }
@ -1754,7 +1754,8 @@ bool EvalState::eqValues(Value& v1, Value& v2) {
} }
/* Otherwise, compare the attributes one by one. */ /* Otherwise, compare the attributes one by one. */
Bindings::iterator i, j; Bindings::iterator i;
Bindings::iterator 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)) { if (i->name != j->name || !eqValues(*i->value, *j->value)) {
@ -1796,7 +1797,8 @@ void EvalState::printStats() {
nrAttrsets * sizeof(Bindings) + nrAttrsInAttrsets * sizeof(Attr); nrAttrsets * sizeof(Bindings) + nrAttrsInAttrsets * sizeof(Attr);
#if HAVE_BOEHMGC #if HAVE_BOEHMGC
GC_word heapSize, totalBytes; GC_word heapSize;
GC_word totalBytes;
GC_get_heap_usage_safe(&heapSize, nullptr, nullptr, nullptr, &totalBytes); GC_get_heap_usage_safe(&heapSize, nullptr, nullptr, nullptr, &totalBytes);
#endif #endif
if (showStats) { if (showStats) {
@ -1927,8 +1929,8 @@ size_t valueSize(Value& v) {
switch (v.type) { switch (v.type) {
case tString: case tString:
sz += doString(v.string.s); sz += doString(v.string.s);
if (v.string.context) { if (v.string.context != nullptr) {
for (const char** p = v.string.context; *p; ++p) { for (const char** p = v.string.context; *p != nullptr; ++p) {
sz += doString(*p); sz += doString(*p);
} }
} }
@ -1993,13 +1995,13 @@ size_t valueSize(Value& v) {
if (env.type != Env::HasWithExpr) { if (env.type != Env::HasWithExpr) {
for (size_t i = 0; i < env.size; ++i) { for (size_t i = 0; i < env.size; ++i) {
if (env.values[i]) { if (env.values[i] != nullptr) {
sz += doValue(*env.values[i]); sz += doValue(*env.values[i]);
} }
} }
} }
if (env.up) { if (env.up != nullptr) {
sz += doEnv(*env.up); sz += doEnv(*env.up);
} }

View file

@ -257,9 +257,9 @@ class EvalState {
Value* allocAttr(Value& vAttrs, const Symbol& name); Value* allocAttr(Value& vAttrs, const Symbol& name);
Bindings* allocBindings(size_t capacity); static Bindings* allocBindings(size_t capacity);
void mkList(Value& v, size_t length); void mkList(Value& v, size_t size);
void mkAttrs(Value& v, size_t capacity); void mkAttrs(Value& v, size_t capacity);
void mkThunk_(Value& v, Expr* expr); void mkThunk_(Value& v, Expr* expr);
void mkPos(Value& v, Pos* pos); void mkPos(Value& v, Pos* pos);

View file

@ -45,7 +45,7 @@ DrvInfo::DrvInfo(EvalState& state, ref<Store> store,
} }
string DrvInfo::queryName() const { string DrvInfo::queryName() const {
if (name == "" && attrs) { if (name.empty() && (attrs != nullptr)) {
auto i = attrs->find(state->sName); auto i = attrs->find(state->sName);
if (i == attrs->end()) { if (i == attrs->end()) {
throw TypeError("derivation name missing"); throw TypeError("derivation name missing");
@ -56,7 +56,7 @@ string DrvInfo::queryName() const {
} }
string DrvInfo::querySystem() const { string DrvInfo::querySystem() const {
if (system == "" && attrs) { if (system.empty() && (attrs != nullptr)) {
auto i = attrs->find(state->sSystem); auto i = attrs->find(state->sSystem);
system = i == attrs->end() ? "unknown" system = i == attrs->end() ? "unknown"
: state->forceStringNoCtx(*i->value, *i->pos); : state->forceStringNoCtx(*i->value, *i->pos);
@ -65,7 +65,7 @@ string DrvInfo::querySystem() const {
} }
string DrvInfo::queryDrvPath() const { string DrvInfo::queryDrvPath() const {
if (drvPath == "" && attrs) { if (drvPath.empty() && (attrs != nullptr)) {
Bindings::iterator i = attrs->find(state->sDrvPath); Bindings::iterator i = attrs->find(state->sDrvPath);
PathSet context; PathSet context;
drvPath = i != attrs->end() drvPath = i != attrs->end()
@ -76,7 +76,7 @@ string DrvInfo::queryDrvPath() const {
} }
string DrvInfo::queryOutPath() const { string DrvInfo::queryOutPath() const {
if (outPath == "" && attrs) { if (outPath.empty() && (attrs != nullptr)) {
Bindings::iterator i = attrs->find(state->sOutPath); Bindings::iterator i = attrs->find(state->sOutPath);
PathSet context; PathSet context;
outPath = i != attrs->end() outPath = i != attrs->end()
@ -90,7 +90,8 @@ DrvInfo::Outputs DrvInfo::queryOutputs(bool onlyOutputsToInstall) {
if (outputs.empty()) { if (outputs.empty()) {
/* Get the outputs list. */ /* Get the outputs list. */
Bindings::iterator i; Bindings::iterator i;
if (attrs && (i = attrs->find(state->sOutputs)) != attrs->end()) { if ((attrs != nullptr) &&
(i = attrs->find(state->sOutputs)) != attrs->end()) {
state->forceList(*i->value, *i->pos); state->forceList(*i->value, *i->pos);
/* For each output... */ /* For each output... */
@ -117,13 +118,13 @@ DrvInfo::Outputs DrvInfo::queryOutputs(bool onlyOutputsToInstall) {
outputs["out"] = queryOutPath(); outputs["out"] = queryOutPath();
} }
} }
if (!onlyOutputsToInstall || !attrs) { if (!onlyOutputsToInstall || (attrs == nullptr)) {
return outputs; 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) { if (outTI == nullptr) {
return outputs; return outputs;
} }
const auto errMsg = Error("this derivation has bad 'meta.outputsToInstall'"); const auto errMsg = Error("this derivation has bad 'meta.outputsToInstall'");
@ -147,7 +148,7 @@ DrvInfo::Outputs DrvInfo::queryOutputs(bool onlyOutputsToInstall) {
} }
string DrvInfo::queryOutputName() const { string DrvInfo::queryOutputName() const {
if (outputName == "" && attrs) { if (outputName.empty() && (attrs != nullptr)) {
Bindings::iterator i = attrs->find(state->sOutputName); Bindings::iterator i = attrs->find(state->sOutputName);
outputName = i != attrs->end() ? state->forceStringNoCtx(*i->value) : ""; outputName = i != attrs->end() ? state->forceStringNoCtx(*i->value) : "";
} }
@ -155,10 +156,10 @@ string DrvInfo::queryOutputName() const {
} }
Bindings* DrvInfo::getMeta() { Bindings* DrvInfo::getMeta() {
if (meta) { if (meta != nullptr) {
return meta; return meta;
} }
if (!attrs) { if (attrs == nullptr) {
return nullptr; return nullptr;
} }
Bindings::iterator a = attrs->find(state->sMeta); Bindings::iterator a = attrs->find(state->sMeta);
@ -172,7 +173,7 @@ Bindings* DrvInfo::getMeta() {
StringSet DrvInfo::queryMetaNames() { StringSet DrvInfo::queryMetaNames() {
StringSet res; StringSet res;
if (!getMeta()) { if (getMeta() == nullptr) {
return res; return res;
} }
for (auto& i : *meta) { for (auto& i : *meta) {
@ -190,7 +191,8 @@ bool DrvInfo::checkMeta(Value& v) {
} }
} }
return true; return true;
} else if (v.type == tAttrs) { }
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()) { if (i != v.attrs->end()) {
return false; return false;
@ -208,7 +210,7 @@ bool DrvInfo::checkMeta(Value& v) {
} }
Value* DrvInfo::queryMeta(const string& name) { Value* DrvInfo::queryMeta(const string& name) {
if (!getMeta()) { if (getMeta() == nullptr) {
return nullptr; return nullptr;
} }
Bindings::iterator a = meta->find(state->symbols.create(name)); Bindings::iterator a = meta->find(state->symbols.create(name));
@ -220,7 +222,7 @@ Value* DrvInfo::queryMeta(const string& name) {
string DrvInfo::queryMetaString(const string& name) { string DrvInfo::queryMetaString(const string& name) {
Value* v = queryMeta(name); Value* v = queryMeta(name);
if (!v || v->type != tString) { if ((v == nullptr) || v->type != tString) {
return ""; return "";
} }
return v->string.s; return v->string.s;
@ -228,7 +230,7 @@ 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) { if (v == nullptr) {
return def; return def;
} }
if (v->type == tInt) { if (v->type == tInt) {
@ -247,7 +249,7 @@ 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) { if (v == nullptr) {
return def; return def;
} }
if (v->type == tFloat) { if (v->type == tFloat) {
@ -266,7 +268,7 @@ 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) { if (v == nullptr) {
return def; return def;
} }
if (v->type == tBool) { if (v->type == tBool) {
@ -288,16 +290,16 @@ bool DrvInfo::queryMetaBool(const string& name, bool def) {
void DrvInfo::setMeta(const string& name, Value* v) { void DrvInfo::setMeta(const string& name, Value* v) {
getMeta(); getMeta();
Bindings* old = meta; Bindings* old = meta;
meta = state->allocBindings(1 + (old ? old->size() : 0)); meta = state->allocBindings(1 + (old != nullptr ? old->size() : 0));
Symbol sym = state->symbols.create(name); Symbol sym = state->symbols.create(name);
if (old) { if (old != nullptr) {
for (auto i : *old) { for (auto i : *old) {
if (i.name != sym) { if (i.name != sym) {
meta->push_back(i); meta->push_back(i);
} }
} }
} }
if (v) { if (v != nullptr) {
meta->push_back(Attr(sym, v)); meta->push_back(Attr(sym, v));
} }
meta->sort(); meta->sort();

View file

@ -16,7 +16,7 @@ static string parseJSONString(const char*& s) {
throw JSONParseError("expected JSON string"); throw JSONParseError("expected JSON string");
} }
while (*s != '"') { while (*s != '"') {
if (!*s) { if (*s == 0) {
throw JSONParseError("got end-of-string in JSON string"); throw JSONParseError("got end-of-string in JSON string");
} }
if (*s == '\\') { if (*s == '\\') {
@ -57,7 +57,7 @@ static string parseJSONString(const char*& s) {
static void parseJSON(EvalState& state, const char*& s, Value& v) { static void parseJSON(EvalState& state, const char*& s, Value& v) {
skipWhitespace(s); skipWhitespace(s);
if (!*s) { if (*s == 0) {
throw JSONParseError("expected JSON value"); throw JSONParseError("expected JSON value");
} }
@ -127,12 +127,13 @@ static void parseJSON(EvalState& state, const char*& s, Value& v) {
mkString(v, parseJSONString(s)); mkString(v, parseJSONString(s));
} }
else if (isdigit(*s) || *s == '-' || *s == '.') { else if ((isdigit(*s) != 0) || *s == '-' || *s == '.') {
// Buffer into a string first, then use built-in C++ conversions // Buffer into a string first, then use built-in C++ conversions
std::string tmp_number; std::string tmp_number;
ValueType number_type = tInt; ValueType number_type = tInt;
while (isdigit(*s) || *s == '-' || *s == '.' || *s == 'e' || *s == 'E') { while ((isdigit(*s) != 0) || *s == '-' || *s == '.' || *s == 'e' ||
*s == 'E') {
if (*s == '.' || *s == 'e' || *s == 'E') { if (*s == '.' || *s == 'e' || *s == 'E') {
number_type = tFloat; number_type = tFloat;
} }
@ -176,7 +177,7 @@ void parseJSON(EvalState& state, const string& s_, Value& v) {
const char* s = s_.c_str(); const char* s = s_.c_str();
parseJSON(state, s, v); parseJSON(state, s, v);
skipWhitespace(s); skipWhitespace(s);
if (*s) { if (*s != 0) {
throw JSONParseError( throw JSONParseError(
format("expected end-of-string while parsing JSON value: %1%") % s); format("expected end-of-string while parsing JSON value: %1%") % s);
} }

View file

@ -17,7 +17,7 @@ DrvName::DrvName(const string& s) : hits(0) {
name = fullName = s; name = fullName = s;
for (unsigned int i = 0; i < s.size(); ++i) { for (unsigned int i = 0; i < s.size(); ++i) {
/* !!! isalpha/isdigit are affected by the locale. */ /* !!! isalpha/isdigit are affected by the locale. */
if (s[i] == '-' && i + 1 < s.size() && !isalpha(s[i + 1])) { if (s[i] == '-' && i + 1 < s.size() && (isalpha(s[i + 1]) == 0)) {
name = string(s, 0, i); name = string(s, 0, i);
version = string(s, i + 1); version = string(s, i + 1);
break; break;
@ -34,10 +34,7 @@ bool DrvName::matches(DrvName& n) {
return false; return false;
} }
} }
if (version != "" && version != n.version) { return !(!version.empty() && version != n.version);
return false;
}
return true;
} }
string nextComponent(string::const_iterator& p, string nextComponent(string::const_iterator& p,
@ -55,12 +52,12 @@ string nextComponent(string::const_iterator& p,
of digits. Otherwise, consume the longest sequence of of digits. Otherwise, consume the longest sequence of
non-digit, non-separator characters. */ non-digit, non-separator characters. */
string s; string s;
if (isdigit(*p)) { if (isdigit(*p) != 0) {
while (p != end && isdigit(*p)) { while (p != end && (isdigit(*p) != 0)) {
s += *p++; s += *p++;
} }
} else { } else {
while (p != end && (!isdigit(*p) && *p != '.' && *p != '-')) { while (p != end && ((isdigit(*p) == 0) && *p != '.' && *p != '-')) {
s += *p++; s += *p++;
} }
} }
@ -69,12 +66,15 @@ string nextComponent(string::const_iterator& p,
} }
static bool componentsLT(const string& c1, const string& c2) { static bool componentsLT(const string& c1, const string& c2) {
int n1, n2; int n1;
bool c1Num = string2Int(c1, n1), c2Num = string2Int(c2, n2); int n2;
bool c1Num = string2Int(c1, n1);
bool c2Num = string2Int(c2, n2);
if (c1Num && c2Num) { if (c1Num && c2Num) {
return n1 < n2; return n1 < n2;
} else if (c1 == "" && c2Num) { }
if (c1.empty() && c2Num) {
return true; return true;
} else if (c1 == "pre" && c2 != "pre") { } else if (c1 == "pre" && c2 != "pre") {
return true; return true;
@ -99,7 +99,8 @@ int compareVersions(const string& v1, const string& v2) {
string c2 = nextComponent(p2, v2.end()); string c2 = nextComponent(p2, v2.end());
if (componentsLT(c1, c2)) { if (componentsLT(c1, c2)) {
return -1; return -1;
} else if (componentsLT(c2, c1)) { }
if (componentsLT(c2, c1)) {
return 1; return 1;
} }
} }

View file

@ -73,7 +73,7 @@ void ExprVar::show(std::ostream& str) const { str << name; }
void ExprSelect::show(std::ostream& str) const { void ExprSelect::show(std::ostream& str) const {
str << "(" << *e << ")." << showAttrPath(attrPath); str << "(" << *e << ")." << showAttrPath(attrPath);
if (def) { if (def != nullptr) {
str << " or (" << *def << ")"; str << " or (" << *def << ")";
} }
} }
@ -121,7 +121,7 @@ void ExprLambda::show(std::ostream& str) const {
str << ", "; str << ", ";
} }
str << i.name; str << i.name;
if (i.def) { if (i.def != nullptr) {
str << " ? " << *i.def; str << " ? " << *i.def;
} }
} }
@ -233,7 +233,8 @@ void ExprVar::bindVars(const StaticEnv& env) {
const StaticEnv* curEnv; const StaticEnv* curEnv;
unsigned int level; unsigned int level;
int withLevel = -1; int withLevel = -1;
for (curEnv = &env, level = 0; curEnv; curEnv = curEnv->up, level++) { for (curEnv = &env, level = 0; curEnv != nullptr;
curEnv = curEnv->up, level++) {
if (curEnv->isWith) { if (curEnv->isWith) {
if (withLevel == -1) { if (withLevel == -1) {
withLevel = level; withLevel = level;
@ -263,7 +264,7 @@ 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) { if (def != nullptr) {
def->bindVars(env); def->bindVars(env);
} }
for (auto& i : attrPath) { for (auto& i : attrPath) {
@ -332,7 +333,7 @@ void ExprLambda::bindVars(const StaticEnv& env) {
} }
for (auto& i : formals->formals) { for (auto& i : formals->formals) {
if (i.def) { if (i.def != nullptr) {
i.def->bindVars(newEnv); i.def->bindVars(newEnv);
} }
} }
@ -363,7 +364,8 @@ 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 != nullptr;
curEnv = curEnv->up, level++) {
if (curEnv->isWith) { if (curEnv->isWith) {
prevWith = level; prevWith = level;
break; break;

View file

@ -37,9 +37,8 @@ std::pair<string, string> decodeContext(const string& s) {
size_t index = s.find("!", 1); size_t index = s.find("!", 1);
return std::pair<string, string>(string(s, index + 1), return std::pair<string, string>(string(s, index + 1),
string(s, 1, index - 1)); string(s, 1, index - 1));
} else {
return std::pair<string, string>(s.at(0) == '/' ? s : string(s, 1), "");
} }
return std::pair<string, string>(s.at(0) == '/' ? s : string(s, 1), "");
} }
InvalidPathError::InvalidPathError(const Path& path) InvalidPathError::InvalidPathError(const Path& path)
@ -83,8 +82,11 @@ void EvalState::realiseContext(const PathSet& context) {
} }
/* For performance, prefetch all substitute info. */ /* For performance, prefetch all substitute info. */
PathSet willBuild, willSubstitute, unknown; PathSet willBuild;
unsigned long long downloadSize, narSize; PathSet willSubstitute;
PathSet unknown;
unsigned long long downloadSize;
unsigned long long narSize;
store->queryMissing(drvs, willBuild, willSubstitute, unknown, downloadSize, store->queryMissing(drvs, willBuild, willSubstitute, unknown, downloadSize,
narSize); narSize);
store->buildPaths(drvs); store->buildPaths(drvs);
@ -181,22 +183,21 @@ void prim_importNative(EvalState& state, const Pos& pos, Value** args,
string sym = state.forceStringNoCtx(*args[1], pos); string sym = state.forceStringNoCtx(*args[1], pos);
void* handle = dlopen(path.c_str(), RTLD_LAZY | RTLD_LOCAL); void* handle = dlopen(path.c_str(), RTLD_LAZY | RTLD_LOCAL);
if (!handle) { if (handle == nullptr) {
throw EvalError(format("could not open '%1%': %2%") % path % dlerror()); throw EvalError(format("could not open '%1%': %2%") % path % dlerror());
} }
dlerror(); dlerror();
auto func = (ValueInitializer)dlsym(handle, sym.c_str()); auto func = (ValueInitializer)dlsym(handle, sym.c_str());
if (!func) { if (func == nullptr) {
char* message = dlerror(); char* message = dlerror();
if (message) { if (message != nullptr) {
throw EvalError(format("could not load symbol '%1%' from '%2%': %3%") % throw EvalError(format("could not load symbol '%1%' from '%2%': %3%") %
sym % path % message); sym % path % message);
} else {
throw EvalError(format("symbol '%1%' from '%2%' resolved to NULL when a "
"function pointer was expected") %
sym % path);
} }
throw EvalError(format("symbol '%1%' from '%2%' resolved to NULL when a "
"function pointer was expected") %
sym % path);
} }
(func)(state, v); (func)(state, v);
@ -765,11 +766,11 @@ static void prim_derivationStrict(EvalState& state, const Pos& pos,
} }
/* Do we have all required attributes? */ /* Do we have all required attributes? */
if (drv.builder == "") { if (drv.builder.empty()) {
throw EvalError(format("required attribute 'builder' missing, at %1%") % throw EvalError(format("required attribute 'builder' missing, at %1%") %
posDrvName); posDrvName);
} }
if (drv.platform == "") { if (drv.platform.empty()) {
throw EvalError(format("required attribute 'system' missing, at %1%") % throw EvalError(format("required attribute 'system' missing, at %1%") %
posDrvName); posDrvName);
} }
@ -822,7 +823,7 @@ static void prim_derivationStrict(EvalState& state, const Pos& pos,
Hash h = hashDerivationModulo(*state.store, drv); Hash h = hashDerivationModulo(*state.store, drv);
for (auto& i : drv.outputs) { for (auto& i : drv.outputs) {
if (i.second.path == "") { if (i.second.path.empty()) {
Path outPath = state.store->makeOutputPath(i.first, h, drvName); Path outPath = state.store->makeOutputPath(i.first, h, drvName);
if (!jsonObject) { if (!jsonObject) {
drv.env[i.first] = outPath; drv.env[i.first] = outPath;
@ -1134,7 +1135,7 @@ static void addPath(EvalState& state, const Pos& pos, const string& name,
const auto path = evalSettings.pureEval && expectedHash const auto path = evalSettings.pureEval && expectedHash
? path_ ? path_
: state.checkSourcePath(path_); : state.checkSourcePath(path_);
PathFilter filter = filterFun ? ([&](const Path& path) { PathFilter filter = filterFun != nullptr ? ([&](const Path& path) {
auto st = lstat(path); auto st = lstat(path);
/* Call the filter function. The first argument is the path, /* Call the filter function. The first argument is the path,
@ -1159,7 +1160,7 @@ static void addPath(EvalState& state, const Pos& pos, const string& name,
return state.forceBool(res, pos); return state.forceBool(res, pos);
}) })
: defaultPathFilter; : defaultPathFilter;
Path expectedStorePath; Path expectedStorePath;
if (expectedHash) { if (expectedHash) {
@ -1305,7 +1306,7 @@ void prim_getAttr(EvalState& state, const Pos& pos, Value** args, Value& v) {
throw EvalError(format("attribute '%1%' missing, at %2%") % attr % pos); throw EvalError(format("attribute '%1%' missing, at %2%") % attr % pos);
} }
// !!! add to stack trace? // !!! add to stack trace?
if (state.countCalls && i->pos) { if (state.countCalls && (i->pos != nullptr)) {
state.attrSelects[*i->pos]++; state.attrSelects[*i->pos]++;
} }
state.forceValue(*i->value); state.forceValue(*i->value);
@ -1485,7 +1486,7 @@ static void prim_functionArgs(EvalState& state, const Pos& pos, Value** args,
state.mkAttrs(v, args[0]->lambda.fun->formals->formals.size()); state.mkAttrs(v, args[0]->lambda.fun->formals->formals.size());
for (auto& i : args[0]->lambda.fun->formals->formals) { for (auto& i : args[0]->lambda.fun->formals->formals) {
// !!! should optimise booleans (allocate only once) // !!! should optimise booleans (allocate only once)
mkBool(*state.allocAttr(v, i.name), i.def); mkBool(*state.allocAttr(v, i.name), i.def != nullptr);
} }
v.attrs->sort(); v.attrs->sort();
} }
@ -1634,7 +1635,7 @@ static void prim_foldlStrict(EvalState& state, const Pos& pos, Value** args,
state.forceFunction(*args[0], pos); state.forceFunction(*args[0], pos);
state.forceList(*args[2], pos); state.forceList(*args[2], pos);
if (args[2]->listSize()) { if (args[2]->listSize() != 0u) {
Value* vCur = args[1]; Value* vCur = args[1];
for (unsigned int n = 0; n < args[2]->listSize(); ++n) { for (unsigned int n = 0; n < args[2]->listSize(); ++n) {
@ -1716,7 +1717,8 @@ static void prim_sort(EvalState& state, const Pos& pos, Value** args,
return CompareValues()(a, b); return CompareValues()(a, b);
} }
Value vTmp1, vTmp2; Value vTmp1;
Value vTmp2;
state.callFunction(*args[0], *a, vTmp1, pos); state.callFunction(*args[0], *a, vTmp1, pos);
state.callFunction(vTmp1, *b, vTmp2, pos); state.callFunction(vTmp1, *b, vTmp2, pos);
return state.forceBool(vTmp2, pos); return state.forceBool(vTmp2, pos);
@ -1735,7 +1737,8 @@ static void prim_partition(EvalState& state, const Pos& pos, Value** args,
auto len = args[1]->listSize(); auto len = args[1]->listSize();
ValueVector right, wrong; ValueVector right;
ValueVector wrong;
for (unsigned int n = 0; n < len; ++n) { for (unsigned int n = 0; n < len; ++n) {
auto vElem = args[1]->listElems()[n]; auto vElem = args[1]->listElems()[n];
@ -1754,14 +1757,14 @@ static void prim_partition(EvalState& state, const Pos& pos, Value** args,
Value* vRight = state.allocAttr(v, state.sRight); Value* vRight = state.allocAttr(v, state.sRight);
auto rsize = right.size(); auto rsize = right.size();
state.mkList(*vRight, rsize); state.mkList(*vRight, rsize);
if (rsize) { if (rsize != 0u) {
memcpy(vRight->listElems(), right.data(), sizeof(Value*) * rsize); memcpy(vRight->listElems(), right.data(), sizeof(Value*) * rsize);
} }
Value* vWrong = state.allocAttr(v, state.sWrong); Value* vWrong = state.allocAttr(v, state.sWrong);
auto wsize = wrong.size(); auto wsize = wrong.size();
state.mkList(*vWrong, wsize); state.mkList(*vWrong, wsize);
if (wsize) { if (wsize != 0u) {
memcpy(vWrong->listElems(), wrong.data(), sizeof(Value*) * wsize); memcpy(vWrong->listElems(), wrong.data(), sizeof(Value*) * wsize);
} }
@ -1790,7 +1793,7 @@ static void prim_concatMap(EvalState& state, const Pos& pos, Value** args,
auto out = v.listElems(); auto out = v.listElems();
for (unsigned int n = 0, pos = 0; n < nrLists; ++n) { for (unsigned int n = 0, pos = 0; n < nrLists; ++n) {
auto l = lists[n].listSize(); auto l = lists[n].listSize();
if (l) { if (l != 0u) {
memcpy(out + pos, lists[n].listElems(), l * sizeof(Value*)); memcpy(out + pos, lists[n].listElems(), l * sizeof(Value*));
} }
pos += l; pos += l;
@ -1971,9 +1974,8 @@ static void prim_match(EvalState& state, const Pos& pos, Value** args,
// limit is _GLIBCXX_REGEX_STATE_LIMIT for libstdc++ // limit is _GLIBCXX_REGEX_STATE_LIMIT for libstdc++
throw EvalError("memory limit exceeded by regular expression '%s', at %s", throw EvalError("memory limit exceeded by regular expression '%s', at %s",
re, pos); re, pos);
} else {
throw EvalError("invalid regular expression '%s', at %s", re, pos);
} }
throw EvalError("invalid regular expression '%s', at %s", re, pos);
} }
} }
@ -2039,9 +2041,8 @@ static void prim_split(EvalState& state, const Pos& pos, Value** args,
// limit is _GLIBCXX_REGEX_STATE_LIMIT for libstdc++ // limit is _GLIBCXX_REGEX_STATE_LIMIT for libstdc++
throw EvalError("memory limit exceeded by regular expression '%s', at %s", throw EvalError("memory limit exceeded by regular expression '%s', at %s",
re, pos); re, pos);
} else {
throw EvalError("invalid regular expression '%s', at %s", re, pos);
} }
throw EvalError("invalid regular expression '%s', at %s", re, pos);
} }
} }
@ -2246,7 +2247,7 @@ static void prim_fetchTarball(EvalState& state, const Pos& pos, Value** args,
RegisterPrimOp::PrimOps* RegisterPrimOp::primOps; RegisterPrimOp::PrimOps* RegisterPrimOp::primOps;
RegisterPrimOp::RegisterPrimOp(std::string name, size_t arity, PrimOpFun fun) { RegisterPrimOp::RegisterPrimOp(std::string name, size_t arity, PrimOpFun fun) {
if (!primOps) { if (primOps == nullptr) {
primOps = new PrimOps; primOps = new PrimOps;
} }
primOps->emplace_back(name, arity, fun); primOps->emplace_back(name, arity, fun);
@ -2444,7 +2445,7 @@ void EvalState::createBaseEnv() {
} }
addConstant("__nixPath", v); addConstant("__nixPath", v);
if (RegisterPrimOp::primOps) { if (RegisterPrimOp::primOps != nullptr) {
for (auto& primOp : *RegisterPrimOp::primOps) { for (auto& primOp : *RegisterPrimOp::primOps) {
addPrimOp(std::get<0>(primOp), std::get<1>(primOp), std::get<2>(primOp)); addPrimOp(std::get<0>(primOp), std::get<1>(primOp), std::get<2>(primOp));
} }

View file

@ -111,7 +111,7 @@ static void printValueAsXML(EvalState& state, bool strict, bool location,
XMLOpenElement _(doc, "derivation", xmlAttrs); XMLOpenElement _(doc, "derivation", xmlAttrs);
if (drvPath != "" && drvsSeen.find(drvPath) == drvsSeen.end()) { if (!drvPath.empty() && drvsSeen.find(drvPath) == drvsSeen.end()) {
drvsSeen.insert(drvPath); drvsSeen.insert(drvPath);
showAttrs(state, strict, location, *v.attrs, doc, context, drvsSeen); showAttrs(state, strict, location, *v.attrs, doc, context, drvsSeen);
} else { } else {

View file

@ -37,8 +37,11 @@ void printGCWarning() {
} }
void printMissing(ref<Store> store, const PathSet& paths) { void printMissing(ref<Store> store, const PathSet& paths) {
unsigned long long downloadSize, narSize; unsigned long long downloadSize;
PathSet willBuild, willSubstitute, unknown; unsigned long long narSize;
PathSet willBuild;
PathSet willSubstitute;
PathSet unknown;
store->queryMissing(paths, willBuild, willSubstitute, unknown, downloadSize, store->queryMissing(paths, willBuild, willSubstitute, unknown, downloadSize,
narSize); narSize);
printMissing(store, willBuild, willSubstitute, unknown, downloadSize, printMissing(store, willBuild, willSubstitute, unknown, downloadSize,
@ -129,13 +132,13 @@ void initNix() {
sigemptyset(&act.sa_mask); sigemptyset(&act.sa_mask);
act.sa_handler = SIG_DFL; act.sa_handler = SIG_DFL;
act.sa_flags = 0; act.sa_flags = 0;
if (sigaction(SIGCHLD, &act, nullptr)) { if (sigaction(SIGCHLD, &act, nullptr) != 0) {
throw SysError("resetting SIGCHLD"); throw SysError("resetting SIGCHLD");
} }
/* Install a dummy SIGUSR1 handler for use with pthread_kill(). */ /* Install a dummy SIGUSR1 handler for use with pthread_kill(). */
act.sa_handler = sigHandler; act.sa_handler = sigHandler;
if (sigaction(SIGUSR1, &act, nullptr)) { if (sigaction(SIGUSR1, &act, nullptr) != 0) {
throw SysError("handling SIGUSR1"); throw SysError("handling SIGUSR1");
} }
@ -319,7 +322,7 @@ int handleExceptions(const string& programName, std::function<void()> fun) {
return 1; return 1;
} catch (BaseError& e) { } catch (BaseError& e) {
LOG(ERROR) << error << (settings.showTrace ? e.prefix() : "") << e.msg(); LOG(ERROR) << error << (settings.showTrace ? e.prefix() : "") << e.msg();
if (e.prefix() != "" && !settings.showTrace) { if (!e.prefix().empty() && !settings.showTrace) {
LOG(INFO) << "(use '--show-trace' to show detailed location information)"; LOG(INFO) << "(use '--show-trace' to show detailed location information)";
} }
return e.status; return e.status;
@ -335,11 +338,11 @@ int handleExceptions(const string& programName, std::function<void()> fun) {
} }
RunPager::RunPager() { RunPager::RunPager() {
if (!isatty(STDOUT_FILENO)) { if (isatty(STDOUT_FILENO) == 0) {
return; return;
} }
char* pager = getenv("NIX_PAGER"); char* pager = getenv("NIX_PAGER");
if (!pager) { if (pager == nullptr) {
pager = getenv("PAGER"); pager = getenv("PAGER");
} }
if (pager && ((string)pager == "" || (string)pager == "cat")) { if (pager && ((string)pager == "" || (string)pager == "cat")) {
@ -353,11 +356,11 @@ RunPager::RunPager() {
if (dup2(toPager.readSide.get(), STDIN_FILENO) == -1) { if (dup2(toPager.readSide.get(), STDIN_FILENO) == -1) {
throw SysError("dupping stdin"); throw SysError("dupping stdin");
} }
if (!getenv("LESS")) { if (getenv("LESS") == nullptr) {
setenv("LESS", "FRSXMK", 1); setenv("LESS", "FRSXMK", 1);
} }
restoreSignals(); restoreSignals();
if (pager) { if (pager != nullptr) {
execl("/bin/sh", "sh", "-c", pager, nullptr); execl("/bin/sh", "sh", "-c", pager, nullptr);
} }
execlp("pager", "pager", nullptr); execlp("pager", "pager", nullptr);

View file

@ -40,7 +40,7 @@ static void sigsegvHandler(int signo, siginfo_t* info, void* ctx) {
sigfillset(&act.sa_mask); sigfillset(&act.sa_mask);
act.sa_handler = SIG_DFL; act.sa_handler = SIG_DFL;
act.sa_flags = 0; act.sa_flags = 0;
if (sigaction(SIGSEGV, &act, nullptr)) { if (sigaction(SIGSEGV, &act, nullptr) != 0) {
abort(); abort();
} }
} }
@ -54,7 +54,7 @@ void detectStackOverflow() {
stack.ss_size = 4096 * 4 + MINSIGSTKSZ; stack.ss_size = 4096 * 4 + MINSIGSTKSZ;
static auto stackBuf = std::make_unique<std::vector<char>>(stack.ss_size); static auto stackBuf = std::make_unique<std::vector<char>>(stack.ss_size);
stack.ss_sp = stackBuf->data(); stack.ss_sp = stackBuf->data();
if (!stack.ss_sp) { if (stack.ss_sp == nullptr) {
throw Error("cannot allocate alternative stack"); throw Error("cannot allocate alternative stack");
} }
stack.ss_flags = 0; stack.ss_flags = 0;
@ -66,7 +66,7 @@ void detectStackOverflow() {
sigfillset(&act.sa_mask); sigfillset(&act.sa_mask);
act.sa_sigaction = sigsegvHandler; act.sa_sigaction = sigsegvHandler;
act.sa_flags = SA_SIGINFO | SA_ONSTACK; act.sa_flags = SA_SIGINFO | SA_ONSTACK;
if (sigaction(SIGSEGV, &act, nullptr)) { if (sigaction(SIGSEGV, &act, nullptr) != 0) {
throw SysError("resetting SIGSEGV"); throw SysError("resetting SIGSEGV");
} }
#endif #endif

View file

@ -120,7 +120,7 @@ void BinaryCacheStore::addToStore(const ValidPathInfo& info,
const ref<std::string>& nar, const ref<std::string>& nar,
RepairFlag repair, CheckSigsFlag checkSigs, RepairFlag repair, CheckSigsFlag checkSigs,
std::shared_ptr<FSAccessor> accessor) { std::shared_ptr<FSAccessor> accessor) {
if (!repair && isValidPath(info.path)) { if ((repair == 0u) && isValidPath(info.path)) {
return; return;
} }
@ -206,7 +206,7 @@ void BinaryCacheStore::addToStore(const ValidPathInfo& info,
: compression == "bzip2" : compression == "bzip2"
? ".bz2" ? ".bz2"
: compression == "br" ? ".br" : ""); : compression == "br" ? ".br" : "");
if (repair || !fileExists(narInfo->url)) { if ((repair != 0u) || !fileExists(narInfo->url)) {
stats.narWrite++; stats.narWrite++;
upsertFile(narInfo->url, *narCompressed, "application/x-nix-nar"); upsertFile(narInfo->url, *narCompressed, "application/x-nix-nar");
} else { } else {
@ -323,7 +323,7 @@ Path BinaryCacheStore::addTextToStore(const string& name, const string& s,
info.path = computeStorePathForText(name, s, references); info.path = computeStorePathForText(name, s, references);
info.references = references; info.references = references;
if (repair || !isValidPath(info.path)) { if ((repair != 0u) || !isValidPath(info.path)) {
StringSink sink; StringSink sink;
dumpString(s, sink); dumpString(s, sink);
addToStore(info, sink.s, repair, CheckSigs, nullptr); addToStore(info, sink.s, repair, CheckSigs, nullptr);
@ -362,7 +362,7 @@ std::shared_ptr<std::string> BinaryCacheStore::getBuildLog(const Path& path) {
try { try {
auto info = queryPathInfo(path); auto info = queryPathInfo(path);
// FIXME: add a "Log" field to .narinfo // FIXME: add a "Log" field to .narinfo
if (info->deriver == "") { if (info->deriver.empty()) {
return nullptr; return nullptr;
} }
drvPath = info->deriver; drvPath = info->deriver;

View file

@ -458,7 +458,7 @@ void handleDiffHook(uid_t uid, uid_t gid, Path tryA, Path tryB, Path drvPath,
statusToString(diffRes.first))); statusToString(diffRes.first)));
} }
if (diffRes.second != "") { if (!diffRes.second.empty()) {
LOG(ERROR) << chomp(diffRes.second); LOG(ERROR) << chomp(diffRes.second);
} }
} catch (Error& error) { } catch (Error& error) {
@ -512,7 +512,7 @@ UserLock::UserLock() {
/* Get the members of the build-users-group. */ /* Get the members of the build-users-group. */
struct group* gr = getgrnam(settings.buildUsersGroup.get().c_str()); struct group* gr = getgrnam(settings.buildUsersGroup.get().c_str());
if (!gr) { if (gr == nullptr) {
throw Error( throw Error(
format( format(
"the group '%1%' specified in 'build-users-group' does not exist") % "the group '%1%' specified in 'build-users-group' does not exist") %
@ -522,7 +522,7 @@ UserLock::UserLock() {
/* Copy the result of getgrnam. */ /* Copy the result of getgrnam. */
Strings users; Strings users;
for (char** p = gr->gr_mem; *p; ++p) { for (char** p = gr->gr_mem; *p != nullptr; ++p) {
DLOG(INFO) << "found build user " << *p; DLOG(INFO) << "found build user " << *p;
users.push_back(*p); users.push_back(*p);
} }
@ -538,7 +538,7 @@ UserLock::UserLock() {
DLOG(INFO) << "trying user " << i; DLOG(INFO) << "trying user " << i;
struct passwd* pw = getpwnam(i.c_str()); struct passwd* pw = getpwnam(i.c_str());
if (!pw) { if (pw == nullptr) {
throw Error(format("the user '%1%' in the group '%2%' does not exist") % throw Error(format("the user '%1%' in the group '%2%' does not exist") %
i % settings.buildUsersGroup); i % settings.buildUsersGroup);
} }
@ -550,7 +550,7 @@ UserLock::UserLock() {
{ {
auto lockedPaths(lockedPaths_.lock()); auto lockedPaths(lockedPaths_.lock());
if (lockedPaths->count(fnUserLock)) { if (lockedPaths->count(fnUserLock) != 0u) {
/* We already have a lock on this one. */ /* We already have a lock on this one. */
continue; continue;
} }
@ -937,7 +937,7 @@ class DerivationGoal : public Goal {
/* Run the builder's process. */ /* Run the builder's process. */
void runChild(); void runChild();
friend int childEntry(void*); friend int childEntry(void* /*arg*/);
/* Check that the derivation outputs all exist and register them /* Check that the derivation outputs all exist and register them
as valid. */ as valid. */
@ -1149,7 +1149,7 @@ void DerivationGoal::haveDerivation() {
PathSet invalidOutputs = checkPathValidity(false, buildMode == bmRepair); PathSet invalidOutputs = checkPathValidity(false, buildMode == bmRepair);
/* If they are all valid, then we're done. */ /* If they are all valid, then we're done. */
if (invalidOutputs.size() == 0 && buildMode == bmNormal) { if (invalidOutputs.empty() && buildMode == bmNormal) {
done(BuildResult::AlreadyValid); done(BuildResult::AlreadyValid);
return; return;
} }
@ -1297,7 +1297,7 @@ void DerivationGoal::repairClosure() {
LOG(ERROR) << "found corrupted or missing path '" << i LOG(ERROR) << "found corrupted or missing path '" << i
<< "' in the output closure of '" << drvPath << "'"; << "' in the output closure of '" << drvPath << "'";
Path drvPath2 = outputsToDrv[i]; Path drvPath2 = outputsToDrv[i];
if (drvPath2 == "") { if (drvPath2.empty()) {
addWaitee(worker.makeSubstitutionGoal(i, Repair)); addWaitee(worker.makeSubstitutionGoal(i, Repair));
} else { } else {
addWaitee(worker.makeDerivationGoal(drvPath2, PathSet(), bmRepair)); addWaitee(worker.makeDerivationGoal(drvPath2, PathSet(), bmRepair));
@ -1676,7 +1676,7 @@ MakeError(NotDeterministic, BuildError)
} }
~LogSink() override { ~LogSink() override {
if (currentLine != "") { if (!currentLine.empty()) {
currentLine += '\n'; currentLine += '\n';
flushLine(); flushLine();
} }
@ -1733,7 +1733,7 @@ MakeError(NotDeterministic, BuildError)
} }
else { else {
st = dynamic_cast<NotDeterministic*>(&e) st = dynamic_cast<NotDeterministic*>(&e) != nullptr
? BuildResult::NotDeterministic ? BuildResult::NotDeterministic
: statusOk(status) : statusOk(status)
? BuildResult::OutputRejected ? BuildResult::OutputRejected
@ -1774,17 +1774,17 @@ HookReply DerivationGoal::tryBuildHook() {
if (string(s, 0, 2) == "# ") { if (string(s, 0, 2) == "# ") {
reply = string(s, 2); reply = string(s, 2);
break; break;
} else {
s += "\n";
std::cerr << s;
} }
s += "\n";
std::cerr << s;
} }
DLOG(INFO) << "hook reply is " << reply; DLOG(INFO) << "hook reply is " << reply;
if (reply == "decline") { if (reply == "decline") {
return rpDecline; return rpDecline;
} else if (reply == "decline-permanently") { }
if (reply == "decline-permanently") {
worker.tryBuildHook = false; worker.tryBuildHook = false;
worker.hook = nullptr; worker.hook = nullptr;
return rpDecline; return rpDecline;
@ -1799,9 +1799,8 @@ HookReply DerivationGoal::tryBuildHook() {
<< chomp(drainFD(worker.hook->fromHook.readSide.get())); << chomp(drainFD(worker.hook->fromHook.readSide.get()));
worker.hook = nullptr; worker.hook = nullptr;
return rpDecline; return rpDecline;
} else {
throw;
} }
throw;
} }
hook = std::move(worker.hook); hook = std::move(worker.hook);
@ -1854,7 +1853,7 @@ PathSet DerivationGoal::exportReferences(PathSet storePaths) {
storePath = worker.store.toStorePath(storePath); storePath = worker.store.toStorePath(storePath);
if (!inputPaths.count(storePath)) { if (inputPaths.count(storePath) == 0u) {
throw BuildError( throw BuildError(
"cannot export references of path '%s' because it is not in the " "cannot export references of path '%s' because it is not in the "
"input closure of the derivation", "input closure of the derivation",
@ -1897,7 +1896,7 @@ static void preloadNSS() {
if (getaddrinfo("this.pre-initializes.the.dns.resolvers.invalid.", "http", if (getaddrinfo("this.pre-initializes.the.dns.resolvers.invalid.", "http",
nullptr, &res) != 0) { nullptr, &res) != 0) {
if (res) { if (res != nullptr) {
freeaddrinfo(res); freeaddrinfo(res);
} }
} }
@ -2167,7 +2166,7 @@ void DerivationGoal::startBuilder() {
for (auto& i : inputPaths) { for (auto& i : inputPaths) {
Path r = worker.store.toRealPath(i); Path r = worker.store.toRealPath(i);
struct stat st; struct stat st;
if (lstat(r.c_str(), &st)) { if (lstat(r.c_str(), &st) != 0) {
throw SysError(format("getting attributes of path '%1%'") % i); throw SysError(format("getting attributes of path '%1%'") % i);
} }
if (S_ISDIR(st.st_mode)) { if (S_ISDIR(st.st_mode)) {
@ -2222,7 +2221,7 @@ void DerivationGoal::startBuilder() {
corresponding to the valid outputs, and rewrite the corresponding to the valid outputs, and rewrite the
contents of the new outputs to replace the dummy strings contents of the new outputs to replace the dummy strings
with the actual hashes. */ with the actual hashes. */
if (validPaths.size() > 0) { if (!validPaths.empty()) {
for (auto& i : validPaths) { for (auto& i : validPaths) {
addHashRewrite(i); addHashRewrite(i);
} }
@ -2241,7 +2240,7 @@ void DerivationGoal::startBuilder() {
} }
if (useChroot && settings.preBuildHook != "" && if (useChroot && settings.preBuildHook != "" &&
dynamic_cast<Derivation*>(drv.get())) { (dynamic_cast<Derivation*>(drv.get()) != nullptr)) {
DLOG(INFO) << "executing pre-build hook '" << settings.preBuildHook << "'"; DLOG(INFO) << "executing pre-build hook '" << settings.preBuildHook << "'";
auto args = auto args =
useChroot ? Strings({drvPath, chrootRootDir}) : Strings({drvPath}); useChroot ? Strings({drvPath, chrootRootDir}) : Strings({drvPath});
@ -2260,7 +2259,7 @@ void DerivationGoal::startBuilder() {
throw Error(format("unknown pre-build hook command '%1%'") % line); throw Error(format("unknown pre-build hook command '%1%'") % line);
} }
} else if (state == stExtraChrootDirs) { } else if (state == stExtraChrootDirs) {
if (line == "") { if (line.empty()) {
state = stBegin; state = stBegin;
} else { } else {
auto p = line.find('='); auto p = line.find('=');
@ -2291,15 +2290,15 @@ void DerivationGoal::startBuilder() {
std::string slaveName(ptsname(builderOut.readSide.get())); std::string slaveName(ptsname(builderOut.readSide.get()));
if (buildUser) { if (buildUser) {
if (chmod(slaveName.c_str(), 0600)) { if (chmod(slaveName.c_str(), 0600) != 0) {
throw SysError("changing mode of pseudoterminal slave"); throw SysError("changing mode of pseudoterminal slave");
} }
if (chown(slaveName.c_str(), buildUser->getUID(), 0)) { if (chown(slaveName.c_str(), buildUser->getUID(), 0) != 0) {
throw SysError("changing owner of pseudoterminal slave"); throw SysError("changing owner of pseudoterminal slave");
} }
} else { } else {
if (grantpt(builderOut.readSide.get())) { if (grantpt(builderOut.readSide.get()) != 0) {
throw SysError("granting access to pseudoterminal slave"); throw SysError("granting access to pseudoterminal slave");
} }
} }
@ -2311,7 +2310,7 @@ void DerivationGoal::startBuilder() {
dirsInChroot[slaveName] = {slaveName, false}; dirsInChroot[slaveName] = {slaveName, false};
#endif #endif
if (unlockpt(builderOut.readSide.get())) { if (unlockpt(builderOut.readSide.get()) != 0) {
throw SysError("unlocking pseudoterminal"); throw SysError("unlocking pseudoterminal");
} }
@ -2322,13 +2321,13 @@ void DerivationGoal::startBuilder() {
// Put the pt into raw mode to prevent \n -> \r\n translation. // Put the pt into raw mode to prevent \n -> \r\n translation.
struct termios term; struct termios term;
if (tcgetattr(builderOut.writeSide.get(), &term)) { if (tcgetattr(builderOut.writeSide.get(), &term) != 0) {
throw SysError("getting pseudoterminal attributes"); throw SysError("getting pseudoterminal attributes");
} }
cfmakeraw(&term); cfmakeraw(&term);
if (tcsetattr(builderOut.writeSide.get(), TCSANOW, &term)) { if (tcsetattr(builderOut.writeSide.get(), TCSANOW, &term) != 0) {
throw SysError("putting pseudoterminal into raw mode"); throw SysError("putting pseudoterminal into raw mode");
} }
@ -2750,7 +2749,7 @@ void setupSeccomp() {
#if HAVE_SECCOMP #if HAVE_SECCOMP
scmp_filter_ctx ctx; scmp_filter_ctx ctx;
if (!(ctx = seccomp_init(SCMP_ACT_ALLOW))) { if ((ctx = seccomp_init(SCMP_ACT_ALLOW)) == nullptr) {
throw SysError("unable to initialize seccomp mode 2"); throw SysError("unable to initialize seccomp mode 2");
} }
@ -2911,7 +2910,7 @@ void DerivationGoal::runChild() {
createDirs(chrootRootDir + "/dev/shm"); createDirs(chrootRootDir + "/dev/shm");
createDirs(chrootRootDir + "/dev/pts"); createDirs(chrootRootDir + "/dev/pts");
ss.push_back("/dev/full"); ss.push_back("/dev/full");
if (settings.systemFeatures.get().count("kvm") && if ((settings.systemFeatures.get().count("kvm") != 0u) &&
pathExists("/dev/kvm")) { pathExists("/dev/kvm")) {
ss.push_back("/dev/kvm"); ss.push_back("/dev/kvm");
} }
@ -2960,9 +2959,8 @@ void DerivationGoal::runChild() {
if (stat(source.c_str(), &st) == -1) { if (stat(source.c_str(), &st) == -1) {
if (optional && errno == ENOENT) { if (optional && errno == ENOENT) {
return; return;
} else {
throw SysError("getting attributes of path '%1%'", source);
} }
throw SysError("getting attributes of path '%1%'", source);
} }
if (S_ISDIR(st.st_mode)) { if (S_ISDIR(st.st_mode)) {
createDirs(target); createDirs(target);
@ -3005,7 +3003,7 @@ void DerivationGoal::runChild() {
if /dev/ptx/ptmx exists). */ if /dev/ptx/ptmx exists). */
if (pathExists("/dev/pts/ptmx") && if (pathExists("/dev/pts/ptmx") &&
!pathExists(chrootRootDir + "/dev/ptmx") && !pathExists(chrootRootDir + "/dev/ptmx") &&
!dirsInChroot.count("/dev/pts")) { (dirsInChroot.count("/dev/pts") == 0u)) {
if (mount("none", (chrootRootDir + "/dev/pts").c_str(), "devpts", 0, if (mount("none", (chrootRootDir + "/dev/pts").c_str(), "devpts", 0,
"newinstance,mode=0620") == 0) { "newinstance,mode=0620") == 0) {
createSymlink("/dev/pts/ptmx", chrootRootDir + "/dev/ptmx"); createSymlink("/dev/pts/ptmx", chrootRootDir + "/dev/ptmx");
@ -3078,8 +3076,8 @@ void DerivationGoal::runChild() {
uname(&utsbuf); uname(&utsbuf);
if (drv->platform == "i686-linux" && if (drv->platform == "i686-linux" &&
(settings.thisSystem == "x86_64-linux" || (settings.thisSystem == "x86_64-linux" ||
(!strcmp(utsbuf.sysname, "Linux") && ((strcmp(utsbuf.sysname, "Linux") == 0) &&
!strcmp(utsbuf.machine, "x86_64")))) { (strcmp(utsbuf.machine, "x86_64") == 0)))) {
if (personality(PER_LINUX32) == -1) { if (personality(PER_LINUX32) == -1) {
throw SysError("cannot set i686-linux personality"); throw SysError("cannot set i686-linux personality");
} }
@ -3422,7 +3420,7 @@ void DerivationGoal::registerOutputs() {
pathExists(redirected)) { pathExists(redirected)) {
replaceValidPath(path, redirected); replaceValidPath(path, redirected);
} }
if (buildMode == bmCheck && redirected != "") { if (buildMode == bmCheck && !redirected.empty()) {
actualPath = redirected; actualPath = redirected;
} }
} }
@ -3442,7 +3440,7 @@ void DerivationGoal::registerOutputs() {
that means that someone else can have interfered with the that means that someone else can have interfered with the
build. Also, the output should be owned by the build build. Also, the output should be owned by the build
user. */ user. */
if ((!S_ISLNK(st.st_mode) && (st.st_mode & (S_IWGRP | S_IWOTH))) || if ((!S_ISLNK(st.st_mode) && ((st.st_mode & (S_IWGRP | S_IWOTH)) != 0u)) ||
(buildUser && st.st_uid != buildUser->getUID())) { (buildUser && st.st_uid != buildUser->getUID())) {
throw BuildError(format("suspicious ownership or permission on '%1%'; " throw BuildError(format("suspicious ownership or permission on '%1%'; "
"rejecting this build output") % "rejecting this build output") %
@ -3555,7 +3553,7 @@ void DerivationGoal::registerOutputs() {
if (settings.runDiffHook || settings.keepFailed) { if (settings.runDiffHook || settings.keepFailed) {
Path dst = worker.store.toRealPath(path + checkSuffix); Path dst = worker.store.toRealPath(path + checkSuffix);
deletePath(dst); deletePath(dst);
if (rename(actualPath.c_str(), dst.c_str())) { if (rename(actualPath.c_str(), dst.c_str()) != 0) {
throw SysError(format("renaming '%1%' to '%2%'") % actualPath % throw SysError(format("renaming '%1%' to '%2%'") % actualPath %
dst); dst);
} }
@ -3568,11 +3566,10 @@ void DerivationGoal::registerOutputs() {
format("derivation '%1%' may not be deterministic: output '%2%' " format("derivation '%1%' may not be deterministic: output '%2%' "
"differs from '%3%'") % "differs from '%3%'") %
drvPath % path % dst); drvPath % path % dst);
} else {
throw NotDeterministic(format("derivation '%1%' may not be "
"deterministic: output '%2%' differs") %
drvPath % path);
} }
throw NotDeterministic(format("derivation '%1%' may not be "
"deterministic: output '%2%' differs") %
drvPath % path);
} }
/* Since we verified the build, it's now ultimately /* Since we verified the build, it's now ultimately
@ -3665,7 +3662,7 @@ void DerivationGoal::registerOutputs() {
Path prev = i.second.path + checkSuffix; Path prev = i.second.path + checkSuffix;
deletePath(prev); deletePath(prev);
Path dst = i.second.path + checkSuffix; Path dst = i.second.path + checkSuffix;
if (rename(i.second.path.c_str(), dst.c_str())) { if (rename(i.second.path.c_str(), dst.c_str()) != 0) {
throw SysError(format("renaming '%1%' to '%2%'") % i.second.path % dst); throw SysError(format("renaming '%1%' to '%2%'") % i.second.path % dst);
} }
} }
@ -3791,11 +3788,11 @@ void DerivationGoal::checkOutputs(
for (auto& i : used) { for (auto& i : used) {
if (allowed) { if (allowed) {
if (!spec.count(i)) { if (spec.count(i) == 0u) {
badPaths.insert(i); badPaths.insert(i);
} }
} else { } else {
if (spec.count(i)) { if (spec.count(i) != 0u) {
badPaths.insert(i); badPaths.insert(i);
} }
} }
@ -3889,7 +3886,7 @@ Path DerivationGoal::openLogFile() {
string baseName = baseNameOf(drvPath); string baseName = baseNameOf(drvPath);
/* Create a log file. */ /* Create a log file. */
Path dir = fmt("%s/%s/%s/", worker.store.logDir, worker.store.drvsLogDir, Path dir = fmt("%s/%s/%s/", worker.store.logDir, nix::LocalStore::drvsLogDir,
string(baseName, 0, 2)); string(baseName, 0, 2));
createDirs(dir); createDirs(dir);
@ -3927,7 +3924,7 @@ void DerivationGoal::closeLogFile() {
} }
void DerivationGoal::deleteTmpDir(bool force) { void DerivationGoal::deleteTmpDir(bool force) {
if (tmpDir != "") { if (!tmpDir.empty()) {
/* Don't keep temporary directories for builtins because they /* Don't keep temporary directories for builtins because they
might have privileged stuff (like a copy of netrc). */ might have privileged stuff (like a copy of netrc). */
if (settings.keepFailed && !force && !drv->isBuiltin()) { if (settings.keepFailed && !force && !drv->isBuiltin()) {
@ -4165,7 +4162,7 @@ void SubstitutionGoal::init() {
worker.store.addTempRoot(storePath); worker.store.addTempRoot(storePath);
/* If the path already exists we're done. */ /* If the path already exists we're done. */
if (!repair && worker.store.isValidPath(storePath)) { if ((repair == 0u) && worker.store.isValidPath(storePath)) {
amDone(ecSuccess); amDone(ecSuccess);
return; return;
} }
@ -4186,7 +4183,7 @@ void SubstitutionGoal::init() {
void SubstitutionGoal::tryNext() { void SubstitutionGoal::tryNext() {
trace("trying next substituter"); trace("trying next substituter");
if (subs.size() == 0) { if (subs.empty()) {
/* None left. Terminate this goal and let someone else deal /* None left. Terminate this goal and let someone else deal
with it. */ with it. */
DLOG(WARNING) DLOG(WARNING)
@ -4241,7 +4238,7 @@ void SubstitutionGoal::tryNext() {
worker.expectedNarSize, info->narSize); worker.expectedNarSize, info->narSize);
maintainExpectedDownload = maintainExpectedDownload =
narInfo && narInfo->fileSize narInfo && (narInfo->fileSize != 0u)
? std::make_unique<MaintainCount<uint64_t>>( ? std::make_unique<MaintainCount<uint64_t>>(
worker.expectedDownloadSize, narInfo->fileSize) worker.expectedDownloadSize, narInfo->fileSize)
: nullptr; : nullptr;
@ -4250,7 +4247,8 @@ void SubstitutionGoal::tryNext() {
signature. LocalStore::addToStore() also checks for this, but signature. LocalStore::addToStore() also checks for this, but
only after we've downloaded the path. */ only after we've downloaded the path. */
if (worker.store.requireSigs && !sub->isTrusted && if (worker.store.requireSigs && !sub->isTrusted &&
!info->checkSignatures(worker.store, worker.store.getPublicKeys())) { (info->checkSignatures(worker.store, worker.store.getPublicKeys()) ==
0u)) {
LOG(WARNING) << "substituter '" << sub->getUri() LOG(WARNING) << "substituter '" << sub->getUri()
<< "' does not have a valid signature for path '" << storePath << "' does not have a valid signature for path '" << storePath
<< "'"; << "'";
@ -4804,10 +4802,10 @@ unsigned int Worker::exitStatus() {
mask |= 0x08; // 104 mask |= 0x08; // 104
} }
if (mask) { if (mask != 0u) {
mask |= 0x60; mask |= 0x60;
} }
return mask ? mask : 1; return mask != 0u ? mask : 1;
} }
bool Worker::pathContentsGood(const Path& path) { bool Worker::pathContentsGood(const Path& path) {
@ -4839,8 +4837,11 @@ void Worker::markContentsGood(const Path& path) {
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
static void primeCache(Store& store, const PathSet& paths) { static void primeCache(Store& store, const PathSet& paths) {
PathSet willBuild, willSubstitute, unknown; PathSet willBuild;
unsigned long long downloadSize, narSize; PathSet willSubstitute;
PathSet unknown;
unsigned long long downloadSize;
unsigned long long narSize;
store.queryMissing(paths, willBuild, willSubstitute, unknown, downloadSize, store.queryMissing(paths, willBuild, willSubstitute, unknown, downloadSize,
narSize); narSize);
@ -4876,7 +4877,7 @@ void LocalStore::buildPaths(const PathSet& drvPaths, BuildMode buildMode) {
for (auto& i : goals) { for (auto& i : goals) {
if (i->getExitCode() != Goal::ecSuccess) { if (i->getExitCode() != Goal::ecSuccess) {
auto* i2 = dynamic_cast<DerivationGoal*>(i.get()); auto* i2 = dynamic_cast<DerivationGoal*>(i.get());
if (i2) { if (i2 != nullptr) {
failed.insert(i2->getDrvPath()); failed.insert(i2->getDrvPath());
} else { } else {
failed.insert(dynamic_cast<SubstitutionGoal*>(i.get())->getStorePath()); failed.insert(dynamic_cast<SubstitutionGoal*>(i.get())->getStorePath());
@ -4939,7 +4940,7 @@ void LocalStore::repairPath(const Path& path) {
/* Since substituting the path didn't work, if we have a valid /* Since substituting the path didn't work, if we have a valid
deriver, then rebuild the deriver. */ deriver, then rebuild the deriver. */
auto deriver = queryPathInfo(path)->deriver; auto deriver = queryPathInfo(path)->deriver;
if (deriver != "" && isValidPath(deriver)) { if (!deriver.empty() && isValidPath(deriver)) {
goals.clear(); goals.clear();
goals.insert(worker.makeDerivationGoal(deriver, StringSet(), bmRepair)); goals.insert(worker.makeDerivationGoal(deriver, StringSet(), bmRepair));
worker.run(goals); worker.run(goals);

View file

@ -23,7 +23,7 @@ Key::Key(const string& s) {
name = ss.first; name = ss.first;
key = ss.second; key = ss.second;
if (name == "" || key == "") { if (name.empty() || key.empty()) {
throw Error("secret key is corrupt"); throw Error("secret key is corrupt");
} }

View file

@ -24,13 +24,13 @@ struct SecretKey : Key {
SecretKey(const std::string& s); SecretKey(const std::string& s);
/* Return a detached signature of the given string. */ /* Return a detached signature of the given string. */
std::string signDetached(const std::string& s) const; std::string signDetached(const std::string& data) const;
PublicKey toPublicKey() const; PublicKey toPublicKey() const;
}; };
struct PublicKey : Key { struct PublicKey : Key {
PublicKey(const std::string& data); PublicKey(const std::string& s);
private: private:
PublicKey(const std::string& name, const std::string& key) : Key(name, key) {} PublicKey(const std::string& name, const std::string& key) : Key(name, key) {}

View file

@ -90,7 +90,7 @@ static string parseString(std::istream& str) {
static Path parsePath(std::istream& str) { static Path parsePath(std::istream& str) {
string s = parseString(str); string s = parseString(str);
if (s.size() == 0 || s[0] != '/') { if (s.empty() || s[0] != '/') {
throw FormatError(format("bad path '%1%' in derivation") % s); throw FormatError(format("bad path '%1%' in derivation") % s);
} }
return s; return s;
@ -197,7 +197,7 @@ 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 != 0; i++) {
if (*i == '\"' || *i == '\\') { if (*i == '\"' || *i == '\\') {
res += "\\"; res += "\\";
res += *i; res += *i;
@ -303,7 +303,7 @@ bool isDerivation(const string& fileName) {
bool BasicDerivation::isFixedOutput() const { bool BasicDerivation::isFixedOutput() const {
return outputs.size() == 1 && outputs.begin()->first == "out" && return outputs.size() == 1 && outputs.begin()->first == "out" &&
outputs.begin()->second.hash != ""; !outputs.begin()->second.hash.empty();
} }
DrvHashes drvHashes; DrvHashes drvHashes;
@ -356,10 +356,11 @@ Hash hashDerivationModulo(Store& store, Derivation drv) {
DrvPathWithOutputs parseDrvPathWithOutputs(const string& s) { DrvPathWithOutputs parseDrvPathWithOutputs(const string& s) {
size_t n = s.find("!"); size_t n = s.find("!");
return n == s.npos ? DrvPathWithOutputs(s, std::set<string>()) return n == std::string::npos
: DrvPathWithOutputs(string(s, 0, n), ? DrvPathWithOutputs(s, std::set<string>())
tokenizeString<std::set<string> >( : DrvPathWithOutputs(
string(s, n + 1), ",")); string(s, 0, n),
tokenizeString<std::set<string> >(string(s, n + 1), ","));
} }
Path makeDrvPathWithOutputs(const Path& drvPath, Path makeDrvPathWithOutputs(const Path& drvPath,

View file

@ -39,9 +39,8 @@ std::string resolveUri(const std::string& uri) {
if (uri.compare(0, 8, "channel:") == 0) { if (uri.compare(0, 8, "channel:") == 0) {
return "https://nixos.org/channels/" + std::string(uri, 8) + return "https://nixos.org/channels/" + std::string(uri, 8) +
"/nixexprs.tar.xz"; "/nixexprs.tar.xz";
} else {
return uri;
} }
return uri;
} }
struct CurlDownloader : public Downloader { struct CurlDownloader : public Downloader {
@ -111,13 +110,13 @@ struct CurlDownloader : public Downloader {
} }
~DownloadItem() { ~DownloadItem() {
if (req) { if (req != nullptr) {
if (active) { if (active) {
curl_multi_remove_handle(downloader.curlm, req); curl_multi_remove_handle(downloader.curlm, req);
} }
curl_easy_cleanup(req); curl_easy_cleanup(req);
} }
if (requestHeaders) { if (requestHeaders != nullptr) {
curl_slist_free_all(requestHeaders); curl_slist_free_all(requestHeaders);
} }
try { try {
@ -214,13 +213,13 @@ struct CurlDownloader : public Downloader {
return ((DownloadItem*)userp)->headerCallback(contents, size, nmemb); return ((DownloadItem*)userp)->headerCallback(contents, size, nmemb);
} }
int progressCallback(double dltotal, double dlnow) { static int progressCallback(double dltotal, double dlnow) {
try { try {
// TODO(tazjin): this had activity nonsense, clean it up // TODO(tazjin): this had activity nonsense, clean it up
} catch (nix::Interrupted&) { } catch (nix::Interrupted&) {
assert(_isInterrupted); assert(_isInterrupted);
} }
return _isInterrupted; return static_cast<int>(_isInterrupted);
} }
static int progressCallbackWrapper(void* userp, double dltotal, static int progressCallbackWrapper(void* userp, double dltotal,
@ -255,7 +254,7 @@ struct CurlDownloader : public Downloader {
} }
void init() { void init() {
if (!req) { if (req == nullptr) {
req = curl_easy_init(); req = curl_easy_init();
} }
@ -314,7 +313,7 @@ struct CurlDownloader : public Downloader {
} }
if (request.verifyTLS) { if (request.verifyTLS) {
if (settings.caFile != "") { if (!settings.caFile.empty()) {
curl_easy_setopt(req, CURLOPT_CAINFO, settings.caFile.c_str()); curl_easy_setopt(req, CURLOPT_CAINFO, settings.caFile.c_str());
} }
} else { } else {
@ -335,7 +334,7 @@ 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 != 0) {
curl_easy_setopt(req, CURLOPT_RESUME_FROM_LARGE, writtenToSink); curl_easy_setopt(req, CURLOPT_RESUME_FROM_LARGE, writtenToSink);
} }
@ -349,7 +348,7 @@ struct CurlDownloader : public Downloader {
char* effectiveUriCStr; char* effectiveUriCStr;
curl_easy_getinfo(req, CURLINFO_EFFECTIVE_URL, &effectiveUriCStr); curl_easy_getinfo(req, CURLINFO_EFFECTIVE_URL, &effectiveUriCStr);
if (effectiveUriCStr) { if (effectiveUriCStr != nullptr) {
result.effectiveUri = effectiveUriCStr; result.effectiveUri = effectiveUriCStr;
} }
@ -461,10 +460,10 @@ struct CurlDownloader : public Downloader {
(!this->request.dataCallback || writtenToSink == 0 || (!this->request.dataCallback || writtenToSink == 0 ||
(acceptRanges && encoding.empty()))) { (acceptRanges && encoding.empty()))) {
int ms = request.baseRetryTimeMs * int ms = request.baseRetryTimeMs *
std::pow(2.0f, attempt - 1 + std::pow(2.0F, attempt - 1 +
std::uniform_real_distribution<>( std::uniform_real_distribution<>(
0.0, 0.5)(downloader.mt19937)); 0.0, 0.5)(downloader.mt19937));
if (writtenToSink) { if (writtenToSink != 0) {
LOG(WARNING) << exc.what() << "; retrying from offset " LOG(WARNING) << exc.what() << "; retrying from offset "
<< writtenToSink << " in " << ms << "ms"; << writtenToSink << " in " << ms << "ms";
} else { } else {
@ -528,7 +527,7 @@ struct CurlDownloader : public Downloader {
workerThread.join(); workerThread.join();
if (curlm) { if (curlm != nullptr) {
curl_multi_cleanup(curlm); curl_multi_cleanup(curlm);
} }
} }
@ -567,7 +566,7 @@ struct CurlDownloader : public Downloader {
/* Set the promises of any finished requests. */ /* Set the promises of any finished requests. */
CURLMsg* msg; CURLMsg* msg;
int left; int left;
while ((msg = curl_multi_info_read(curlm, &left))) { while ((msg = curl_multi_info_read(curlm, &left)) != nullptr) {
if (msg->msg == CURLMSG_DONE) { if (msg->msg == CURLMSG_DONE) {
auto i = items.find(msg->easy_handle); auto i = items.find(msg->easy_handle);
assert(i != items.end()); assert(i != items.end());
@ -605,7 +604,7 @@ struct CurlDownloader : public Downloader {
/* Add new curl requests from the incoming requests queue, /* Add new curl requests from the incoming requests queue,
except for requests that are embargoed (waiting for a except for requests that are embargoed (waiting for a
retry timeout to expire). */ retry timeout to expire). */
if (extraFDs[0].revents & CURL_WAIT_POLLIN) { if ((extraFDs[0].revents & CURL_WAIT_POLLIN) != 0) {
char buf[1024]; char buf[1024];
auto res = read(extraFDs[0].fd, buf, sizeof(buf)); auto res = read(extraFDs[0].fd, buf, sizeof(buf));
if (res == -1 && errno != EINTR) { if (res == -1 && errno != EINTR) {
@ -863,7 +862,7 @@ CachedDownloadResult Downloader::downloadCached(
auto url = resolveUri(request.uri); auto url = resolveUri(request.uri);
auto name = request.name; auto name = request.name;
if (name == "") { if (name.empty()) {
auto p = url.rfind('/'); auto p = url.rfind('/');
if (p != string::npos) { if (p != string::npos) {
name = string(url, p + 1); name = string(url, p + 1);
@ -987,7 +986,7 @@ CachedDownloadResult Downloader::downloadCached(
storePath = unpackedStorePath; storePath = unpackedStorePath;
} }
if (expectedStorePath != "" && storePath != expectedStorePath) { if (!expectedStorePath.empty() && storePath != expectedStorePath) {
unsigned int statusCode = 102; unsigned int statusCode = 102;
Hash gotHash = Hash gotHash =
request.unpack request.unpack

View file

@ -87,7 +87,7 @@ Paths Store::importPaths(Source& source, std::shared_ptr<FSAccessor> accessor,
info.references = readStorePaths<PathSet>(*this, source); info.references = readStorePaths<PathSet>(*this, source);
info.deriver = readString(source); info.deriver = readString(source);
if (info.deriver != "") { if (!info.deriver.empty()) {
assertStorePath(info.deriver); assertStorePath(info.deriver);
} }

View file

@ -236,7 +236,8 @@ void LocalStore::findTempRoots(FDs& fds, Roots& tempRoots, bool censor) {
string contents = readFile(fd->get()); string contents = readFile(fd->get());
/* Extract the roots. */ /* Extract the roots. */
string::size_type pos = 0, end; string::size_type pos = 0;
string::size_type end;
while ((end = contents.find((char)0, pos)) != string::npos) { while ((end = contents.find((char)0, pos)) != string::npos) {
Path root(contents, pos, end - pos); Path root(contents, pos, end - pos);
@ -542,7 +543,7 @@ void LocalStore::deletePathRecursive(GCState& state, const Path& path) {
Path realPath = realStoreDir + "/" + baseNameOf(path); Path realPath = realStoreDir + "/" + baseNameOf(path);
struct stat st; struct stat st;
if (lstat(realPath.c_str(), &st)) { if (lstat(realPath.c_str(), &st) != 0) {
if (errno == ENOENT) { if (errno == ENOENT) {
return; return;
} }
@ -567,7 +568,7 @@ void LocalStore::deletePathRecursive(GCState& state, const Path& path) {
throw SysError(format("making '%1%' writable") % realPath); throw SysError(format("making '%1%' writable") % realPath);
} }
Path tmp = trashDir + "/" + baseNameOf(path); Path tmp = trashDir + "/" + baseNameOf(path);
if (rename(realPath.c_str(), tmp.c_str())) { if (rename(realPath.c_str(), tmp.c_str()) != 0) {
throw SysError(format("unable to rename '%1%' to '%2%'") % realPath % throw SysError(format("unable to rename '%1%' to '%2%'") % realPath %
tmp); tmp);
} }
@ -593,19 +594,19 @@ void LocalStore::deletePathRecursive(GCState& state, const Path& path) {
bool LocalStore::canReachRoot(GCState& state, PathSet& visited, bool LocalStore::canReachRoot(GCState& state, PathSet& visited,
const Path& path) { const Path& path) {
if (visited.count(path)) { if (visited.count(path) != 0u) {
return false; return false;
} }
if (state.alive.count(path)) { if (state.alive.count(path) != 0u) {
return true; return true;
} }
if (state.dead.count(path)) { if (state.dead.count(path) != 0u) {
return false; return false;
} }
if (state.roots.count(path)) { if (state.roots.count(path) != 0u) {
DLOG(INFO) << "cannot delete '" << path << "' because it's a root"; DLOG(INFO) << "cannot delete '" << path << "' because it's a root";
state.alive.insert(path); state.alive.insert(path);
return true; return true;
@ -713,7 +714,8 @@ void LocalStore::removeUnusedLinks(const GCState& state) {
throw SysError(format("opening directory '%1%'") % linksDir); throw SysError(format("opening directory '%1%'") % linksDir);
} }
long long actualSize = 0, unsharedSize = 0; long long actualSize = 0;
long long unsharedSize = 0;
struct dirent* dirent; struct dirent* dirent;
while (errno = 0, dirent = readdir(dir.get())) { while (errno = 0, dirent = readdir(dir.get())) {
@ -930,7 +932,7 @@ void LocalStore::autoGC(bool sync) {
} }
struct statvfs st; struct statvfs st;
if (statvfs(realStoreDir.c_str(), &st)) { if (statvfs(realStoreDir.c_str(), &st) != 0) {
throw SysError("getting filesystem info about '%s'", realStoreDir); throw SysError("getting filesystem info about '%s'", realStoreDir);
} }

View file

@ -46,7 +46,7 @@ Settings::Settings()
lockCPU = getEnv("NIX_AFFINITY_HACK", "1") == "1"; lockCPU = getEnv("NIX_AFFINITY_HACK", "1") == "1";
caFile = getEnv("NIX_SSL_CERT_FILE", getEnv("SSL_CERT_FILE", "")); caFile = getEnv("NIX_SSL_CERT_FILE", getEnv("SSL_CERT_FILE", ""));
if (caFile == "") { if (caFile.empty()) {
for (auto& fn : for (auto& fn :
{"/etc/ssl/certs/ca-certificates.crt", {"/etc/ssl/certs/ca-certificates.crt",
"/nix/var/nix/profiles/default/etc/ssl/certs/ca-bundle.crt"}) { "/nix/var/nix/profiles/default/etc/ssl/certs/ca-bundle.crt"}) {
@ -59,7 +59,7 @@ Settings::Settings()
/* Backwards compatibility. */ /* Backwards compatibility. */
auto s = getEnv("NIX_REMOTE_SYSTEMS"); auto s = getEnv("NIX_REMOTE_SYSTEMS");
if (s != "") { if (!s.empty()) {
Strings ss; Strings ss;
for (auto& p : tokenizeString<Strings>(s, ":")) { for (auto& p : tokenizeString<Strings>(s, ":")) {
ss.push_back("@" + p); ss.push_back("@" + p);
@ -128,7 +128,8 @@ template <>
std::string BaseSetting<SandboxMode>::to_string() { std::string BaseSetting<SandboxMode>::to_string() {
if (value == smEnabled) { if (value == smEnabled) {
return "true"; return "true";
} else if (value == smRelaxed) { }
if (value == smRelaxed) {
return "relaxed"; return "relaxed";
} else if (value == smDisabled) { } else if (value == smDisabled) {
return "false"; return "false";
@ -189,7 +190,7 @@ void initPlugins() {
/* handle is purposefully leaked as there may be state in the /* handle is purposefully leaked as there may be state in the
DSO needed by the action of the plugin. */ DSO needed by the action of the plugin. */
void* handle = dlopen(file.c_str(), RTLD_LAZY | RTLD_LOCAL); void* handle = dlopen(file.c_str(), RTLD_LAZY | RTLD_LOCAL);
if (!handle) { if (handle == nullptr) {
throw Error("could not dynamically open plugin file '%s': %s", file, throw Error("could not dynamically open plugin file '%s': %s", file,
dlerror()); dlerror());
} }

View file

@ -25,9 +25,9 @@ struct MaxBuildJobsSetting : public BaseSetting<unsigned int> {
}; };
class Settings : public Config { class Settings : public Config {
unsigned int getDefaultCores(); static unsigned int getDefaultCores();
StringSet getDefaultSystemFeatures(); static StringSet getDefaultSystemFeatures();
public: public:
Settings(); Settings();

View file

@ -58,7 +58,7 @@ struct LegacySSHStore : public Store {
auto conn = make_ref<Connection>(); auto conn = make_ref<Connection>();
conn->sshConn = master.startCommand( conn->sshConn = master.startCommand(
fmt("%s --serve --write", remoteProgram) + fmt("%s --serve --write", remoteProgram) +
(remoteStore.get() == "" (remoteStore.get().empty()
? "" ? ""
: " --store " + shellEscape(remoteStore.get()))); : " --store " + shellEscape(remoteStore.get())));
conn->to = FdSink(conn->sshConn->in.get()); conn->to = FdSink(conn->sshConn->in.get());
@ -120,7 +120,7 @@ struct LegacySSHStore : public Store {
} }
auto s = readString(conn->from); auto s = readString(conn->from);
assert(s == ""); assert(s.empty());
callback(std::move(info)); callback(std::move(info));
} catch (...) { } catch (...) {
@ -139,8 +139,8 @@ struct LegacySSHStore : public Store {
if (GET_PROTOCOL_MINOR(conn->remoteVersion) >= 5) { if (GET_PROTOCOL_MINOR(conn->remoteVersion) >= 5) {
conn->to << cmdAddToStoreNar << info.path << info.deriver conn->to << cmdAddToStoreNar << info.path << info.deriver
<< info.narHash.to_string(Base16, false) << info.references << info.narHash.to_string(Base16, false) << info.references
<< info.registrationTime << info.narSize << info.ultimate << info.registrationTime << info.narSize
<< info.sigs << info.ca; << static_cast<uint64_t>(info.ultimate) << info.sigs << info.ca;
try { try {
copyNAR(source, conn->to); copyNAR(source, conn->to);
} catch (...) { } catch (...) {
@ -201,7 +201,8 @@ struct LegacySSHStore : public Store {
conn->to << settings.maxLogSize; conn->to << settings.maxLogSize;
} }
if (GET_PROTOCOL_MINOR(conn->remoteVersion) >= 3) { if (GET_PROTOCOL_MINOR(conn->remoteVersion) >= 3) {
conn->to << settings.buildRepeat << settings.enforceDeterminism; conn->to << settings.buildRepeat
<< static_cast<uint64_t>(settings.enforceDeterminism);
} }
conn->to.flush(); conn->to.flush();
@ -231,7 +232,8 @@ struct LegacySSHStore : public Store {
auto conn(connections->get()); auto conn(connections->get());
conn->to << cmdQueryClosure << includeOutputs << paths; conn->to << cmdQueryClosure << static_cast<uint64_t>(includeOutputs)
<< paths;
conn->to.flush(); conn->to.flush();
auto res = readStorePaths<PathSet>(*this, conn->from); auto res = readStorePaths<PathSet>(*this, conn->from);
@ -243,7 +245,7 @@ struct LegacySSHStore : public Store {
NoSubstitute) override { NoSubstitute) override {
auto conn(connections->get()); auto conn(connections->get());
conn->to << cmdQueryValidPaths << false // lock conn->to << cmdQueryValidPaths << 0u // lock
<< maybeSubstitute << paths; << maybeSubstitute << paths;
conn->to.flush(); conn->to.flush();

View file

@ -59,7 +59,7 @@ static void atomicWrite(const Path& path, const std::string& s) {
Path tmp = path + ".tmp." + std::to_string(getpid()); Path tmp = path + ".tmp." + std::to_string(getpid());
AutoDelete del(tmp, false); AutoDelete del(tmp, false);
writeFile(tmp, s); writeFile(tmp, s);
if (rename(tmp.c_str(), path.c_str())) { if (rename(tmp.c_str(), path.c_str()) != 0) {
throw SysError(format("renaming '%1%' to '%2%'") % tmp % path); throw SysError(format("renaming '%1%' to '%2%'") % tmp % path);
} }
del.cancel(); del.cancel();

View file

@ -27,7 +27,7 @@ struct LocalStoreAccessor : public FSAccessor {
auto realPath = toRealPath(path); auto realPath = toRealPath(path);
struct stat st; struct stat st;
if (lstat(realPath.c_str(), &st)) { if (lstat(realPath.c_str(), &st) != 0) {
if (errno == ENOENT || errno == ENOTDIR) { if (errno == ENOENT || errno == ENOTDIR) {
return {Type::tMissing, 0, false}; return {Type::tMissing, 0, false};
} }
@ -42,7 +42,7 @@ struct LocalStoreAccessor : public FSAccessor {
? Type::tRegular ? Type::tRegular
: S_ISLNK(st.st_mode) ? Type::tSymlink : Type::tDirectory, : S_ISLNK(st.st_mode) ? Type::tSymlink : Type::tDirectory,
S_ISREG(st.st_mode) ? (uint64_t)st.st_size : 0, S_ISREG(st.st_mode) ? (uint64_t)st.st_size : 0,
S_ISREG(st.st_mode) && st.st_mode & S_IXUSR}; S_ISREG(st.st_mode) && ((st.st_mode & S_IXUSR) != 0u)};
} }
StringSet readDirectory(const Path& path) override { StringSet readDirectory(const Path& path) override {
@ -92,7 +92,7 @@ std::shared_ptr<std::string> LocalFSStore::getBuildLog(const Path& path_) {
} catch (InvalidPath&) { } catch (InvalidPath&) {
return nullptr; return nullptr;
} }
if (path == "") { if (path.empty()) {
return nullptr; return nullptr;
} }
} }
@ -107,8 +107,8 @@ std::shared_ptr<std::string> LocalFSStore::getBuildLog(const Path& path_) {
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)) { if (pathExists(logBz2Path)) {
try { try {
return decompress("bzip2", readFile(logBz2Path)); return decompress("bzip2", readFile(logBz2Path));
} catch (Error&) { } catch (Error&) {

View file

@ -86,12 +86,12 @@ LocalStore::LocalStore(const Params& params)
mode_t perm = 01775; mode_t perm = 01775;
struct group* gr = getgrnam(settings.buildUsersGroup.get().c_str()); struct group* gr = getgrnam(settings.buildUsersGroup.get().c_str());
if (!gr) { if (gr == nullptr) {
LOG(ERROR) << "warning: the group '" << settings.buildUsersGroup LOG(ERROR) << "warning: the group '" << settings.buildUsersGroup
<< "' specified in 'build-users-group' does not exist"; << "' specified in 'build-users-group' does not exist";
} else { } else {
struct stat st; struct stat st;
if (stat(realStoreDir.c_str(), &st)) { if (stat(realStoreDir.c_str(), &st) != 0) {
throw SysError(format("getting attributes of path '%1%'") % throw SysError(format("getting attributes of path '%1%'") %
realStoreDir); realStoreDir);
} }
@ -115,7 +115,7 @@ LocalStore::LocalStore(const Params& params)
Path path = realStoreDir; Path path = realStoreDir;
struct stat st; struct stat st;
while (path != "/") { while (path != "/") {
if (lstat(path.c_str(), &st)) { if (lstat(path.c_str(), &st) != 0) {
throw SysError(format("getting status of '%1%'") % path); throw SysError(format("getting status of '%1%'") % path);
} }
if (S_ISLNK(st.st_mode)) { if (S_ISLNK(st.st_mode)) {
@ -153,7 +153,7 @@ LocalStore::LocalStore(const Params& params)
/* Acquire the big fat lock in shared mode to make sure that no /* Acquire the big fat lock in shared mode to make sure that no
schema upgrade is in progress. */ schema upgrade is in progress. */
Path globalLockPath = dbDir + "/big-lock"; Path globalLockPath = dbDir + "/big-lock";
globalLock = openLockFile(globalLockPath.c_str(), true); globalLock = openLockFile(globalLockPath, true);
if (!lockFile(globalLock.get(), ltRead, false)) { if (!lockFile(globalLock.get(), ltRead, false)) {
LOG(INFO) << "waiting for the big Nix store lock..."; LOG(INFO) << "waiting for the big Nix store lock...";
@ -168,8 +168,8 @@ LocalStore::LocalStore(const Params& params)
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 */ 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());
@ -311,7 +311,7 @@ int LocalStore::getSchema() {
} }
void LocalStore::openDB(State& state, bool create) { void LocalStore::openDB(State& state, bool create) {
if (access(dbDir.c_str(), R_OK | W_OK)) { if (access(dbDir.c_str(), R_OK | W_OK) != 0) {
throw SysError(format("Nix database directory '%1%' is not writable") % throw SysError(format("Nix database directory '%1%' is not writable") %
dbDir); dbDir);
} }
@ -399,7 +399,7 @@ void LocalStore::makeStoreWritable() {
throw SysError("getting info about the Nix store mount point"); throw SysError("getting info about the Nix store mount point");
} }
if (stat.f_flag & ST_RDONLY) { if ((stat.f_flag & ST_RDONLY) != 0u) {
if (unshare(CLONE_NEWNS) == -1) { if (unshare(CLONE_NEWNS) == -1) {
throw SysError("setting up a private mount namespace"); throw SysError("setting up a private mount namespace");
} }
@ -421,7 +421,8 @@ static void canonicaliseTimestampAndPermissions(const Path& path,
mode_t mode = st.st_mode & ~S_IFMT; mode_t mode = st.st_mode & ~S_IFMT;
if (mode != 0444 && mode != 0555) { if (mode != 0444 && mode != 0555) {
mode = (st.st_mode & S_IFMT) | 0444 | (st.st_mode & S_IXUSR ? 0111 : 0); mode = (st.st_mode & S_IFMT) | 0444 |
((st.st_mode & S_IXUSR) != 0u ? 0111 : 0);
if (chmod(path.c_str(), mode) == -1) { if (chmod(path.c_str(), mode) == -1) {
throw SysError(format("changing mode of '%1%' to %2$o") % path % mode); throw SysError(format("changing mode of '%1%' to %2$o") % path % mode);
} }
@ -449,7 +450,7 @@ static void canonicaliseTimestampAndPermissions(const Path& path,
void canonicaliseTimestampAndPermissions(const Path& path) { void canonicaliseTimestampAndPermissions(const Path& path) {
struct stat st; struct stat st;
if (lstat(path.c_str(), &st)) { if (lstat(path.c_str(), &st) != 0) {
throw SysError(format("getting attributes of path '%1%'") % path); throw SysError(format("getting attributes of path '%1%'") % path);
} }
canonicaliseTimestampAndPermissions(path, st); canonicaliseTimestampAndPermissions(path, st);
@ -470,7 +471,7 @@ static void canonicalisePathMetaData_(const Path& path, uid_t fromUid,
#endif #endif
struct stat st; struct stat st;
if (lstat(path.c_str(), &st)) { if (lstat(path.c_str(), &st) != 0) {
throw SysError(format("getting attributes of path '%1%'") % path); throw SysError(format("getting attributes of path '%1%'") % path);
} }
@ -564,7 +565,7 @@ void canonicalisePathMetaData(const Path& path, uid_t fromUid,
/* On platforms that don't have lchown(), the top-level path can't /* On platforms that don't have lchown(), the top-level path can't
be a symlink, since we can't change its ownership. */ be a symlink, since we can't change its ownership. */
struct stat st; struct stat st;
if (lstat(path.c_str(), &st)) { if (lstat(path.c_str(), &st) != 0) {
throw SysError(format("getting attributes of path '%1%'") % path); throw SysError(format("getting attributes of path '%1%'") % path);
} }
@ -632,7 +633,7 @@ void LocalStore::checkDerivationOutputs(const Path& drvPath,
uint64_t LocalStore::addValidPath(State& state, const ValidPathInfo& info, uint64_t LocalStore::addValidPath(State& state, const ValidPathInfo& info,
bool checkOutputs) { bool checkOutputs) {
if (info.ca != "" && !info.isContentAddressed(*this)) { if (!info.ca.empty() && !info.isContentAddressed(*this)) {
throw Error( throw Error(
"cannot add path '%s' to the Nix store because it claims to be " "cannot add path '%s' to the Nix store because it claims to be "
"content-addressed but isn't", "content-addressed but isn't",
@ -642,7 +643,7 @@ uint64_t LocalStore::addValidPath(State& state, const ValidPathInfo& info,
state.stmtRegisterValidPath state.stmtRegisterValidPath
.use()(info.path)(info.narHash.to_string(Base16))( .use()(info.path)(info.narHash.to_string(Base16))(
info.registrationTime == 0 ? time(nullptr) : info.registrationTime)( info.registrationTime == 0 ? time(nullptr) : info.registrationTime)(
info.deriver, info.deriver != "")(info.narSize, info.narSize != 0)( info.deriver, !info.deriver.empty())(info.narSize, info.narSize != 0)(
info.ultimate ? 1 : 0, info.ultimate)( info.ultimate ? 1 : 0, info.ultimate)(
concatStringsSep(" ", info.sigs), !info.sigs.empty())( concatStringsSep(" ", info.sigs), !info.sigs.empty())(
info.ca, !info.ca.empty()) info.ca, !info.ca.empty())
@ -709,7 +710,7 @@ void LocalStore::queryPathInfoUncached(
info->registrationTime = useQueryPathInfo.getInt(2); info->registrationTime = useQueryPathInfo.getInt(2);
auto s = (const char*)sqlite3_column_text(state->stmtQueryPathInfo, 3); auto s = (const char*)sqlite3_column_text(state->stmtQueryPathInfo, 3);
if (s) { if (s != nullptr) {
info->deriver = s; info->deriver = s;
} }
@ -719,12 +720,12 @@ void LocalStore::queryPathInfoUncached(
info->ultimate = useQueryPathInfo.getInt(5) == 1; info->ultimate = useQueryPathInfo.getInt(5) == 1;
s = (const char*)sqlite3_column_text(state->stmtQueryPathInfo, 6); s = (const char*)sqlite3_column_text(state->stmtQueryPathInfo, 6);
if (s) { if (s != nullptr) {
info->sigs = tokenizeString<StringSet>(s, " "); info->sigs = tokenizeString<StringSet>(s, " ");
} }
s = (const char*)sqlite3_column_text(state->stmtQueryPathInfo, 7); s = (const char*)sqlite3_column_text(state->stmtQueryPathInfo, 7);
if (s) { if (s != nullptr) {
info->ca = s; info->ca = s;
} }
@ -880,8 +881,10 @@ Path LocalStore::queryPathFromHashPart(const string& hashPart) {
const char* s = const char* s =
(const char*)sqlite3_column_text(state->stmtQueryPathFromHashPart, 0); (const char*)sqlite3_column_text(state->stmtQueryPathFromHashPart, 0);
return s && prefix.compare(0, prefix.size(), s, prefix.size()) == 0 ? s return (s != nullptr) &&
: ""; prefix.compare(0, prefix.size(), s, prefix.size()) == 0
? s
: "";
}); });
} }
@ -908,7 +911,7 @@ PathSet LocalStore::querySubstitutablePaths(const PathSet& paths) {
PathSet remaining2; PathSet remaining2;
for (auto& path : remaining) { for (auto& path : remaining) {
if (valid.count(path)) { if (valid.count(path) != 0u) {
res.insert(path); res.insert(path);
} else { } else {
remaining2.insert(path); remaining2.insert(path);
@ -931,7 +934,7 @@ void LocalStore::querySubstitutablePathInfos(const PathSet& paths,
continue; continue;
} }
for (auto& path : paths) { for (auto& path : paths) {
if (infos.count(path)) { if (infos.count(path) != 0u) {
continue; continue;
} }
DLOG(INFO) << "checking substituter '" << sub->getUri() << "' for path '" DLOG(INFO) << "checking substituter '" << sub->getUri() << "' for path '"
@ -1049,15 +1052,15 @@ void LocalStore::addToStore(const ValidPathInfo& info, Source& source,
throw Error("cannot add path '%s' because it lacks a hash", info.path); throw Error("cannot add path '%s' because it lacks a hash", info.path);
} }
if (requireSigs && checkSigs && if (requireSigs && (checkSigs != 0u) &&
!info.checkSignatures(*this, getPublicKeys())) { (info.checkSignatures(*this, getPublicKeys()) == 0u)) {
throw Error("cannot add path '%s' because it lacks a valid signature", throw Error("cannot add path '%s' because it lacks a valid signature",
info.path); info.path);
} }
addTempRoot(info.path); addTempRoot(info.path);
if (repair || !isValidPath(info.path)) { if ((repair != 0u) || !isValidPath(info.path)) {
PathLocks outputLock; PathLocks outputLock;
Path realPath = realStoreDir + "/" + baseNameOf(info.path); Path realPath = realStoreDir + "/" + baseNameOf(info.path);
@ -1065,11 +1068,11 @@ void LocalStore::addToStore(const ValidPathInfo& info, Source& source,
/* Lock the output path. But don't lock if we're being called /* Lock the output path. But don't lock if we're being called
from a build hook (whose parent process already acquired a from a build hook (whose parent process already acquired a
lock on this path). */ lock on this path). */
if (!locksHeld.count(info.path)) { if (locksHeld.count(info.path) == 0u) {
outputLock.lockPaths({realPath}); outputLock.lockPaths({realPath});
} }
if (repair || !isValidPath(info.path)) { if ((repair != 0u) || !isValidPath(info.path)) {
deletePath(realPath); deletePath(realPath);
/* While restoring the path from the NAR, compute the hash /* While restoring the path from the NAR, compute the hash
@ -1121,7 +1124,7 @@ Path LocalStore::addToStoreFromDump(const string& dump, const string& name,
addTempRoot(dstPath); addTempRoot(dstPath);
if (repair || !isValidPath(dstPath)) { if ((repair != 0u) || !isValidPath(dstPath)) {
/* The first check above is an optimisation to prevent /* The first check above is an optimisation to prevent
unnecessary lock acquisition. */ unnecessary lock acquisition. */
@ -1129,7 +1132,7 @@ Path LocalStore::addToStoreFromDump(const string& dump, const string& name,
PathLocks outputLock({realPath}); PathLocks outputLock({realPath});
if (repair || !isValidPath(dstPath)) { if ((repair != 0u) || !isValidPath(dstPath)) {
deletePath(realPath); deletePath(realPath);
autoGC(); autoGC();
@ -1196,12 +1199,12 @@ Path LocalStore::addTextToStore(const string& name, const string& s,
addTempRoot(dstPath); addTempRoot(dstPath);
if (repair || !isValidPath(dstPath)) { if ((repair != 0u) || !isValidPath(dstPath)) {
Path realPath = realStoreDir + "/" + baseNameOf(dstPath); Path realPath = realStoreDir + "/" + baseNameOf(dstPath);
PathLocks outputLock({realPath}); PathLocks outputLock({realPath});
if (repair || !isValidPath(dstPath)) { if ((repair != 0u) || !isValidPath(dstPath)) {
deletePath(realPath); deletePath(realPath);
autoGC(); autoGC();
@ -1286,7 +1289,9 @@ bool LocalStore::verifyStore(bool checkContents, RepairFlag repair) {
/* Check whether all valid paths actually exist. */ /* Check whether all valid paths actually exist. */
LOG(INFO) << "checking path existence..."; LOG(INFO) << "checking path existence...";
PathSet validPaths2 = queryAllValidPaths(), validPaths, done; PathSet validPaths2 = queryAllValidPaths();
PathSet validPaths;
PathSet done;
fdGCLock = -1; fdGCLock = -1;
@ -1313,7 +1318,7 @@ bool LocalStore::verifyStore(bool checkContents, RepairFlag repair) {
LOG(ERROR) << "path '" << i << "' was modified! expected hash '" LOG(ERROR) << "path '" << i << "' was modified! expected hash '"
<< info->narHash.to_string() << "', got '" << info->narHash.to_string() << "', got '"
<< current.first.to_string() << "'"; << current.first.to_string() << "'";
if (repair) { if (repair != 0u) {
repairPath(i); repairPath(i);
} else { } else {
errors = true; errors = true;
@ -1398,7 +1403,7 @@ 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) { if (repair != 0u) {
try { try {
repairPath(path); repairPath(path);
} catch (Error& e) { } catch (Error& e) {

View file

@ -217,7 +217,7 @@ class LocalStore : public LocalFSStore {
void makeStoreWritable(); void makeStoreWritable();
uint64_t queryValidPathId(State& state, const Path& path); static uint64_t queryValidPathId(State& state, const Path& path);
uint64_t addValidPath(State& state, const ValidPathInfo& info, uint64_t addValidPath(State& state, const ValidPathInfo& info,
bool checkOutputs = true); bool checkOutputs = true);
@ -230,7 +230,7 @@ class LocalStore : public LocalFSStore {
void verifyPath(const Path& path, const PathSet& store, PathSet& done, void verifyPath(const Path& path, const PathSet& store, PathSet& done,
PathSet& validPaths, RepairFlag repair, bool& errors); PathSet& validPaths, RepairFlag repair, bool& errors);
void updatePathInfo(State& state, const ValidPathInfo& info); static void updatePathInfo(State& state, const ValidPathInfo& info);
void upgradeStore6(); void upgradeStore6();
void upgradeStore7(); void upgradeStore7();
@ -239,7 +239,7 @@ class LocalStore : public LocalFSStore {
struct GCState; struct GCState;
void deleteGarbage(GCState& state, const Path& path); static void deleteGarbage(GCState& state, const Path& path);
void tryToDelete(GCState& state, const Path& path); void tryToDelete(GCState& state, const Path& path);
@ -247,8 +247,8 @@ class LocalStore : public LocalFSStore {
void deletePathRecursive(GCState& state, const Path& path); void deletePathRecursive(GCState& state, const Path& path);
bool isActiveTempFile(const GCState& state, const Path& path, static bool isActiveTempFile(const GCState& state, const Path& path,
const string& suffix); const string& suffix);
AutoCloseFD openGCLock(LockType lockType); AutoCloseFD openGCLock(LockType lockType);
@ -267,18 +267,19 @@ class LocalStore : public LocalFSStore {
typedef std::unordered_set<ino_t> InodeHash; typedef std::unordered_set<ino_t> InodeHash;
InodeHash loadInodeHash(); InodeHash loadInodeHash();
Strings readDirectoryIgnoringInodes(const Path& path, static Strings readDirectoryIgnoringInodes(const Path& path,
const InodeHash& inodeHash); const InodeHash& inodeHash);
void optimisePath_(OptimiseStats& stats, const Path& path, void optimisePath_(OptimiseStats& stats, const Path& path,
InodeHash& inodeHash); InodeHash& inodeHash);
// Internal versions that are not wrapped in retry_sqlite. // Internal versions that are not wrapped in retry_sqlite.
bool isValidPath_(State& state, const Path& path); static bool isValidPath_(State& state, const Path& path);
void queryReferrers(State& state, const Path& path, PathSet& referrers); static void queryReferrers(State& state, const Path& path,
PathSet& referrers);
/* Add signatures to a ValidPathInfo using the secret keys /* Add signatures to a ValidPathInfo using the secret keys
specified by the secret-key-files option. */ specified by the secret-key-files option. */
void signPathInfo(ValidPathInfo& info); static void signPathInfo(ValidPathInfo& info);
Path getRealStoreDir() override { return realStoreDir; } Path getRealStoreDir() override { return realStoreDir; }

View file

@ -35,8 +35,8 @@ Machine::Machine(decltype(storeUri) storeUri, decltype(systemTypes) systemTypes,
bool Machine::allSupported(const std::set<string>& features) const { bool Machine::allSupported(const std::set<string>& features) const {
return std::all_of(features.begin(), features.end(), return std::all_of(features.begin(), features.end(),
[&](const string& feature) { [&](const string& feature) {
return supportedFeatures.count(feature) || return (supportedFeatures.count(feature) != 0u) ||
mandatoryFeatures.count(feature); (mandatoryFeatures.count(feature) != 0u);
}); });
} }
@ -74,7 +74,7 @@ void parseMachines(const std::string& s, Machines& machines) {
} }
auto isSet = [&](size_t n) { auto isSet = [&](size_t n) {
return tokens.size() > n && tokens[n] != "" && tokens[n] != "-"; return tokens.size() > n && !tokens[n].empty() && tokens[n] != "-";
}; };
machines.emplace_back( machines.emplace_back(

View file

@ -30,7 +30,7 @@ void Store::computeFSClosure(const PathSet& startPaths, PathSet& paths_,
if (state->exc) { if (state->exc) {
return; return;
} }
if (state->paths.count(path)) { if (state->paths.count(path) != 0u) {
return; return;
} }
state->paths.insert(path); state->paths.insert(path);
@ -90,7 +90,7 @@ void Store::computeFSClosure(const PathSet& startPaths, PathSet& paths_,
{ {
auto state(state_.lock()); auto state(state_.lock());
assert(state->pending); assert(state->pending);
if (!--state->pending) { if (--state->pending == 0u) {
done.notify_one(); done.notify_one();
} }
} }
@ -101,7 +101,7 @@ void Store::computeFSClosure(const PathSet& startPaths, PathSet& paths_,
state->exc = std::current_exception(); state->exc = std::current_exception();
} }
assert(state->pending); assert(state->pending);
if (!--state->pending) { if (--state->pending == 0u) {
done.notify_one(); done.notify_one();
} }
}; };
@ -114,7 +114,7 @@ void Store::computeFSClosure(const PathSet& startPaths, PathSet& paths_,
{ {
auto state(state_.lock()); auto state(state_.lock());
while (state->pending) { while (state->pending != 0u) {
state.wait(done); state.wait(done);
} }
if (state->exc) { if (state->exc) {
@ -192,7 +192,7 @@ void Store::queryMissing(const PathSet& targets, PathSet& willBuild_,
assert(drvState->left); assert(drvState->left);
drvState->left--; drvState->left--;
drvState->outPaths.insert(outPath); drvState->outPaths.insert(outPath);
if (!drvState->left) { if (drvState->left == 0u) {
for (auto& path : drvState->outPaths) { for (auto& path : drvState->outPaths) {
pool.enqueue(std::bind(doPath, path)); pool.enqueue(std::bind(doPath, path));
} }
@ -204,7 +204,7 @@ void Store::queryMissing(const PathSet& targets, PathSet& willBuild_,
doPath = [&](const Path& path) { doPath = [&](const Path& path) {
{ {
auto state(state_.lock()); auto state(state_.lock());
if (state->done.count(path)) { if (state->done.count(path) != 0u) {
return; return;
} }
state->done.insert(path); state->done.insert(path);
@ -282,7 +282,8 @@ void Store::queryMissing(const PathSet& targets, PathSet& willBuild_,
Paths Store::topoSortPaths(const PathSet& paths) { Paths Store::topoSortPaths(const PathSet& paths) {
Paths sorted; Paths sorted;
PathSet visited, parents; PathSet visited;
PathSet parents;
std::function<void(const Path& path, const Path* parent)> dfsVisit; std::function<void(const Path& path, const Path* parent)> dfsVisit;

View file

@ -132,7 +132,7 @@ struct NarAccessor : public FSAccessor {
} }
NarMember* find(const Path& path) { NarMember* find(const Path& path) {
Path canon = path == "" ? "" : canonPath(path); Path canon = path.empty() ? "" : canonPath(path);
NarMember* current = &root; NarMember* current = &root;
auto end = path.end(); auto end = path.end();
for (auto it = path.begin(); it != end;) { for (auto it = path.begin(); it != end;) {
@ -238,7 +238,7 @@ void listNar(JSONPlaceholder& res, ref<FSAccessor> accessor, const Path& path,
if (st.isExecutable) { if (st.isExecutable) {
obj.attr("executable", true); obj.attr("executable", true);
} }
if (st.narOffset) { if (st.narOffset != 0u) {
obj.attr("narOffset", st.narOffset); obj.attr("narOffset", st.narOffset);
} }
break; break;

View file

@ -142,7 +142,7 @@ class NarInfoDiskCacheImpl : public NarInfoDiskCache {
}); });
} }
Cache& getCache(State& state, const std::string& uri) { static Cache& getCache(State& state, const std::string& uri) {
auto i = state.caches.find(uri); auto i = state.caches.find(uri);
if (i == state.caches.end()) { if (i == state.caches.end()) {
abort(); abort();
@ -158,7 +158,8 @@ class NarInfoDiskCacheImpl : public NarInfoDiskCache {
// FIXME: race // FIXME: race
state->insertCache state->insertCache
.use()(uri)(time(nullptr))(storeDir)(wantMassQuery)(priority) .use()(uri)(time(nullptr))(storeDir)(
static_cast<int64_t>(wantMassQuery))(priority)
.exec(); .exec();
assert(sqlite3_changes(state->db) == 1); assert(sqlite3_changes(state->db) == 1);
state->caches[uri] = Cache{(int)sqlite3_last_insert_rowid(state->db), state->caches[uri] = Cache{(int)sqlite3_last_insert_rowid(state->db),
@ -209,7 +210,7 @@ class NarInfoDiskCacheImpl : public NarInfoDiskCache {
return {oUnknown, nullptr}; return {oUnknown, nullptr};
} }
if (!queryNAR.getInt(0)) { if (queryNAR.getInt(0) == 0) {
return {oInvalid, nullptr}; return {oInvalid, nullptr};
} }
@ -262,10 +263,10 @@ class NarInfoDiskCacheImpl : public NarInfoDiskCache {
narInfo && narInfo->fileHash)( narInfo && narInfo->fileHash)(
narInfo ? narInfo->fileSize : 0, narInfo ? narInfo->fileSize : 0,
narInfo != nullptr && narInfo != nullptr &&
narInfo->fileSize)(info->narHash.to_string())( (narInfo->fileSize != 0u))(info->narHash.to_string())(
info->narSize)(concatStringsSep(" ", info->shortRefs()))( info->narSize)(concatStringsSep(" ", info->shortRefs()))(
info->deriver != "" ? baseNameOf(info->deriver) : "", !info->deriver.empty() ? baseNameOf(info->deriver) : "",
info->deriver != "")(concatStringsSep(" ", info->sigs))( !info->deriver.empty())(concatStringsSep(" ", info->sigs))(
info->ca)(time(nullptr)) info->ca)(time(nullptr))
.exec(); .exec();

View file

@ -90,7 +90,7 @@ NarInfo::NarInfo(const Store& store, const std::string& s,
pos = eol + 1; pos = eol + 1;
} }
if (compression == "") { if (compression.empty()) {
compression = "bzip2"; compression = "bzip2";
} }
@ -103,7 +103,7 @@ std::string NarInfo::to_string() const {
std::string res; std::string res;
res += "StorePath: " + path + "\n"; res += "StorePath: " + path + "\n";
res += "URL: " + url + "\n"; res += "URL: " + url + "\n";
assert(compression != ""); assert(!compression.empty());
res += "Compression: " + compression + "\n"; res += "Compression: " + compression + "\n";
assert(fileHash.type == htSHA256); assert(fileHash.type == htSHA256);
res += "FileHash: " + fileHash.to_string(Base32) + "\n"; res += "FileHash: " + fileHash.to_string(Base32) + "\n";

View file

@ -18,7 +18,7 @@ namespace nix {
static void makeWritable(const Path& path) { static void makeWritable(const Path& path) {
struct stat st; struct stat st;
if (lstat(path.c_str(), &st)) { if (lstat(path.c_str(), &st) != 0) {
throw SysError(format("getting attributes of path '%1%'") % path); throw SysError(format("getting attributes of path '%1%'") % path);
} }
if (chmod(path.c_str(), st.st_mode | S_IWUSR) == -1) { if (chmod(path.c_str(), st.st_mode | S_IWUSR) == -1) {
@ -32,7 +32,7 @@ struct MakeReadOnly {
~MakeReadOnly() { ~MakeReadOnly() {
try { try {
/* This will make the path read-only. */ /* This will make the path read-only. */
if (path != "") { if (!path.empty()) {
canonicaliseTimestampAndPermissions(path); canonicaliseTimestampAndPermissions(path);
} }
} catch (...) { } catch (...) {
@ -78,7 +78,7 @@ Strings LocalStore::readDirectoryIgnoringInodes(const Path& path,
while (errno = 0, dirent = readdir(dir.get())) { /* sic */ while (errno = 0, dirent = readdir(dir.get())) { /* sic */
checkInterrupt(); checkInterrupt();
if (inodeHash.count(dirent->d_ino)) { if (inodeHash.count(dirent->d_ino) != 0u) {
DLOG(WARNING) << dirent->d_name << " is already linked"; DLOG(WARNING) << dirent->d_name << " is already linked";
continue; continue;
} }
@ -101,7 +101,7 @@ void LocalStore::optimisePath_(OptimiseStats& stats, const Path& path,
checkInterrupt(); checkInterrupt();
struct stat st; struct stat st;
if (lstat(path.c_str(), &st)) { if (lstat(path.c_str(), &st) != 0) {
throw SysError(format("getting attributes of path '%1%'") % path); throw SysError(format("getting attributes of path '%1%'") % path);
} }
@ -137,13 +137,13 @@ void LocalStore::optimisePath_(OptimiseStats& stats, const Path& path,
modified, in particular when running programs as root under modified, in particular when running programs as root under
NixOS (example: $fontconfig/var/cache being modified). Skip NixOS (example: $fontconfig/var/cache being modified). Skip
those files. FIXME: check the modification time. */ those files. FIXME: check the modification time. */
if (S_ISREG(st.st_mode) && (st.st_mode & S_IWUSR)) { if (S_ISREG(st.st_mode) && ((st.st_mode & S_IWUSR) != 0u)) {
LOG(WARNING) << "skipping suspicious writable file '" << path << "'"; LOG(WARNING) << "skipping suspicious writable file '" << path << "'";
return; return;
} }
/* This can still happen on top-level files. */ /* This can still happen on top-level files. */
if (st.st_nlink > 1 && inodeHash.count(st.st_ino)) { if (st.st_nlink > 1 && (inodeHash.count(st.st_ino) != 0u)) {
DLOG(INFO) << path << " is already linked, with " << (st.st_nlink - 2) DLOG(INFO) << path << " is already linked, with " << (st.st_nlink - 2)
<< " other file(s)"; << " other file(s)";
return; return;
@ -196,7 +196,7 @@ retry:
/* Yes! We've seen a file with the same contents. Replace the /* Yes! We've seen a file with the same contents. Replace the
current file with a hard link to that file. */ current file with a hard link to that file. */
struct stat stLink; struct stat stLink;
if (lstat(linkPath.c_str(), &stLink)) { if (lstat(linkPath.c_str(), &stLink) != 0) {
throw SysError(format("getting attributes of path '%1%'") % linkPath); throw SysError(format("getting attributes of path '%1%'") % linkPath);
} }
@ -234,7 +234,7 @@ retry:
/* Too many links to the same file (>= 32000 on most file /* Too many links to the same file (>= 32000 on most file
systems). This is likely to happen with empty files. systems). This is likely to happen with empty files.
Just shrug and ignore. */ Just shrug and ignore. */
if (st.st_size) { if (st.st_size != 0) {
LOG(WARNING) << linkPath << " has maximum number of links"; LOG(WARNING) << linkPath << " has maximum number of links";
} }
return; return;

View file

@ -22,20 +22,19 @@ std::optional<std::string> ParsedDerivation::getStringAttr(
auto i = structuredAttrs->find(name); auto i = structuredAttrs->find(name);
if (i == structuredAttrs->end()) { if (i == structuredAttrs->end()) {
return {}; return {};
} else {
if (!i->is_string()) {
throw Error("attribute '%s' of derivation '%s' must be a string", name,
drvPath);
}
return i->get<std::string>();
} }
if (!i->is_string()) {
throw Error("attribute '%s' of derivation '%s' must be a string", name,
drvPath);
}
return i->get<std::string>();
} else { } else {
auto i = drv.env.find(name); auto i = drv.env.find(name);
if (i == drv.env.end()) { if (i == drv.env.end()) {
return {}; return {};
} else {
return i->second;
} }
return i->second;
} }
} }
@ -44,20 +43,19 @@ bool ParsedDerivation::getBoolAttr(const std::string& name, bool def) const {
auto i = structuredAttrs->find(name); auto i = structuredAttrs->find(name);
if (i == structuredAttrs->end()) { if (i == structuredAttrs->end()) {
return def; return def;
} else {
if (!i->is_boolean()) {
throw Error("attribute '%s' of derivation '%s' must be a Boolean", name,
drvPath);
}
return i->get<bool>();
} }
if (!i->is_boolean()) {
throw Error("attribute '%s' of derivation '%s' must be a Boolean", name,
drvPath);
}
return i->get<bool>();
} else { } else {
auto i = drv.env.find(name); auto i = drv.env.find(name);
if (i == drv.env.end()) { if (i == drv.env.end()) {
return def; return def;
} else {
return i->second == "1";
} }
return i->second == "1";
} }
} }
@ -67,30 +65,28 @@ std::optional<Strings> ParsedDerivation::getStringsAttr(
auto i = structuredAttrs->find(name); auto i = structuredAttrs->find(name);
if (i == structuredAttrs->end()) { if (i == structuredAttrs->end()) {
return {}; return {};
} else { }
if (!i->is_array()) { if (!i->is_array()) {
throw Error("attribute '%s' of derivation '%s' must be a list of strings",
name, drvPath);
}
Strings res;
for (const auto& j : *i) {
if (!j.is_string()) {
throw Error( throw Error(
"attribute '%s' of derivation '%s' must be a list of strings", name, "attribute '%s' of derivation '%s' must be a list of strings", name,
drvPath); drvPath);
} }
Strings res; res.push_back(j.get<std::string>());
for (const auto& j : *i) {
if (!j.is_string()) {
throw Error(
"attribute '%s' of derivation '%s' must be a list of strings",
name, drvPath);
}
res.push_back(j.get<std::string>());
}
return res;
} }
return res;
} else { } else {
auto i = drv.env.find(name); auto i = drv.env.find(name);
if (i == drv.env.end()) { if (i == drv.env.end()) {
return {}; return {};
} else {
return tokenizeString<Strings>(i->second);
} }
return tokenizeString<Strings>(i->second);
} }
} }
@ -104,12 +100,13 @@ StringSet ParsedDerivation::getRequiredSystemFeatures() const {
bool ParsedDerivation::canBuildLocally() const { bool ParsedDerivation::canBuildLocally() const {
if (drv.platform != settings.thisSystem.get() && if (drv.platform != settings.thisSystem.get() &&
!settings.extraPlatforms.get().count(drv.platform) && !drv.isBuiltin()) { (settings.extraPlatforms.get().count(drv.platform) == 0u) &&
!drv.isBuiltin()) {
return false; return false;
} }
for (auto& feature : getRequiredSystemFeatures()) { for (auto& feature : getRequiredSystemFeatures()) {
if (!settings.systemFeatures.get().count(feature)) { if (settings.systemFeatures.get().count(feature) == 0u) {
return false; return false;
} }
} }

View file

@ -53,9 +53,8 @@ bool lockFile(int fd, LockType lockType, bool wait) {
checkInterrupt(); checkInterrupt();
if (errno != EINTR) { if (errno != EINTR) {
throw SysError(format("acquiring/releasing lock")); throw SysError(format("acquiring/releasing lock"));
} else {
return false;
} }
return false;
} }
} else { } else {
while (flock(fd, type | LOCK_NB) != 0) { while (flock(fd, type | LOCK_NB) != 0) {
@ -104,7 +103,7 @@ bool PathLocks::lockPaths(const PathSet& paths, const string& waitMsg,
/* Acquire an exclusive lock. */ /* Acquire an exclusive lock. */
if (!lockFile(fd.get(), ltWrite, false)) { if (!lockFile(fd.get(), ltWrite, false)) {
if (wait) { if (wait) {
if (waitMsg != "") { if (!waitMsg.empty()) {
LOG(WARNING) << waitMsg; LOG(WARNING) << waitMsg;
} }
lockFile(fd.get(), ltWrite, true); lockFile(fd.get(), ltWrite, true);

View file

@ -31,9 +31,8 @@ static int parseName(const string& profileName, const string& name) {
int n; int n;
if (string2Int(string(s, 0, p), n) && n >= 0) { if (string2Int(string(s, 0, p), n) && n >= 0) {
return n; return n;
} else {
return -1;
} }
return -1;
} }
Generations findGenerations(Path profile, int& curGen) { Generations findGenerations(Path profile, int& curGen) {
@ -76,7 +75,7 @@ Path createGeneration(ref<LocalFSStore> store, Path profile, Path outPath) {
Generations gens = findGenerations(profile, dummy); Generations gens = findGenerations(profile, dummy);
unsigned int num; unsigned int num;
if (gens.size() > 0) { if (!gens.empty()) {
Generation last = gens.back(); Generation last = gens.back();
if (readLink(last.path) == outPath) { if (readLink(last.path) == outPath) {
@ -165,7 +164,7 @@ void deleteGenerationsGreaterThan(const Path& profile, int max, bool dryRun) {
continue; continue;
} }
if (fromCurGen) { if (fromCurGen) {
if (max) { if (max != 0) {
max--; max--;
continue; continue;
} }

View file

@ -11,14 +11,14 @@ namespace nix {
RemoteFSAccessor::RemoteFSAccessor(ref<Store> store, const Path& cacheDir) RemoteFSAccessor::RemoteFSAccessor(ref<Store> store, const Path& cacheDir)
: store(store), cacheDir(cacheDir) { : store(store), cacheDir(cacheDir) {
if (cacheDir != "") { if (!cacheDir.empty()) {
createDirs(cacheDir); createDirs(cacheDir);
} }
} }
Path RemoteFSAccessor::makeCacheFile(const Path& storePath, Path RemoteFSAccessor::makeCacheFile(const Path& storePath,
const std::string& ext) { const std::string& ext) {
assert(cacheDir != ""); assert(!cacheDir.empty());
return fmt("%s/%s.%s", cacheDir, storePathToHash(storePath), ext); return fmt("%s/%s.%s", cacheDir, storePathToHash(storePath), ext);
} }
@ -26,7 +26,7 @@ void RemoteFSAccessor::addToCache(const Path& storePath, const std::string& nar,
ref<FSAccessor> narAccessor) { ref<FSAccessor> narAccessor) {
nars.emplace(storePath, narAccessor); nars.emplace(storePath, narAccessor);
if (cacheDir != "") { if (!cacheDir.empty()) {
try { try {
std::ostringstream str; std::ostringstream str;
JSONPlaceholder jsonRoot(str); JSONPlaceholder jsonRoot(str);
@ -62,7 +62,7 @@ std::pair<ref<FSAccessor>, Path> RemoteFSAccessor::fetch(const Path& path_) {
std::string listing; std::string listing;
Path cacheFile; Path cacheFile;
if (cacheDir != "" && if (!cacheDir.empty() &&
pathExists(cacheFile = makeCacheFile(storePath, "nar"))) { pathExists(cacheFile = makeCacheFile(storePath, "nar"))) {
try { try {
listing = nix::readFile(makeCacheFile(storePath, "ls")); listing = nix::readFile(makeCacheFile(storePath, "ls"));

View file

@ -81,9 +81,8 @@ UDSRemoteStore::UDSRemoteStore(std::string socket_path, const Params& params)
std::string UDSRemoteStore::getUri() { std::string UDSRemoteStore::getUri() {
if (path) { if (path) {
return std::string("unix://") + *path; return std::string("unix://") + *path;
} else {
return "daemon";
} }
return "daemon";
} }
ref<RemoteStore::Connection> UDSRemoteStore::openConnection() { ref<RemoteStore::Connection> UDSRemoteStore::openConnection() {
@ -155,7 +154,7 @@ void RemoteStore::initConnection(Connection& conn) {
} }
if (GET_PROTOCOL_MINOR(conn.daemonVersion) >= 11) { if (GET_PROTOCOL_MINOR(conn.daemonVersion) >= 11) {
conn.to << false; conn.to << 0u;
} }
auto ex = conn.processStderr(); auto ex = conn.processStderr();
@ -171,17 +170,18 @@ void RemoteStore::initConnection(Connection& conn) {
} }
void RemoteStore::setOptions(Connection& conn) { void RemoteStore::setOptions(Connection& conn) {
conn.to << wopSetOptions << settings.keepFailed conn.to << wopSetOptions << static_cast<uint64_t>(settings.keepFailed)
<< settings.keepGoing << static_cast<uint64_t>(settings.keepGoing)
// TODO(tazjin): Remove the verbosity stuff here. // TODO(tazjin): Remove the verbosity stuff here.
<< settings.tryFallback << compat::kInfo << settings.maxBuildJobs << static_cast<uint64_t>(settings.tryFallback) << compat::kInfo
<< settings.maxSilentTime << settings.maxBuildJobs << settings.maxSilentTime
<< true << 1u
// TODO(tazjin): what behaviour does this toggle remotely? // TODO(tazjin): what behaviour does this toggle remotely?
<< (settings.verboseBuild ? compat::kError : compat::kVomit) << (settings.verboseBuild ? compat::kError : compat::kVomit)
<< 0 // obsolete log type << 0 // obsolete log type
<< 0 /* obsolete print build trace */ << 0 /* obsolete print build trace */
<< settings.buildCores << settings.useSubstitutes; << settings.buildCores
<< static_cast<uint64_t>(settings.useSubstitutes);
if (GET_PROTOCOL_MINOR(conn.daemonVersion) >= 12) { if (GET_PROTOCOL_MINOR(conn.daemonVersion) >= 12) {
std::map<std::string, Config::SettingInfo> overrides; std::map<std::string, Config::SettingInfo> overrides;
@ -221,7 +221,7 @@ struct ConnectionHandle {
ConnectionHandle(ConnectionHandle&& h) : handle(std::move(h.handle)) {} ConnectionHandle(ConnectionHandle&& h) : handle(std::move(h.handle)) {}
~ConnectionHandle() { ~ConnectionHandle() {
if (!daemonException && std::uncaught_exceptions()) { if (!daemonException && (std::uncaught_exceptions() != 0)) {
handle.markBad(); handle.markBad();
// TODO(tazjin): are these types of things supposed to be DEBUG? // TODO(tazjin): are these types of things supposed to be DEBUG?
DLOG(INFO) << "closing daemon connection because of an exception"; DLOG(INFO) << "closing daemon connection because of an exception";
@ -247,7 +247,7 @@ bool RemoteStore::isValidPathUncached(const Path& path) {
auto conn(getConnection()); auto conn(getConnection());
conn->to << wopIsValidPath << path; conn->to << wopIsValidPath << path;
conn.processStderr(); conn.processStderr();
return readInt(conn->from); return readInt(conn->from) != 0u;
} }
PathSet RemoteStore::queryValidPaths(const PathSet& paths, PathSet RemoteStore::queryValidPaths(const PathSet& paths,
@ -261,11 +261,10 @@ PathSet RemoteStore::queryValidPaths(const PathSet& paths,
} }
} }
return res; return res;
} else {
conn->to << wopQueryValidPaths << paths;
conn.processStderr();
return readStorePaths<PathSet>(*this, conn->from);
} }
conn->to << wopQueryValidPaths << paths;
conn.processStderr();
return readStorePaths<PathSet>(*this, conn->from);
} }
PathSet RemoteStore::queryAllValidPaths() { PathSet RemoteStore::queryAllValidPaths() {
@ -282,16 +281,15 @@ PathSet RemoteStore::querySubstitutablePaths(const PathSet& paths) {
for (auto& i : paths) { for (auto& i : paths) {
conn->to << wopHasSubstitutes << i; conn->to << wopHasSubstitutes << i;
conn.processStderr(); conn.processStderr();
if (readInt(conn->from)) { if (readInt(conn->from) != 0u) {
res.insert(i); res.insert(i);
} }
} }
return res; return res;
} else {
conn->to << wopQuerySubstitutablePaths << paths;
conn.processStderr();
return readStorePaths<PathSet>(*this, conn->from);
} }
conn->to << wopQuerySubstitutablePaths << paths;
conn.processStderr();
return readStorePaths<PathSet>(*this, conn->from);
} }
void RemoteStore::querySubstitutablePathInfos(const PathSet& paths, void RemoteStore::querySubstitutablePathInfos(const PathSet& paths,
@ -312,7 +310,7 @@ void RemoteStore::querySubstitutablePathInfos(const PathSet& paths,
continue; continue;
} }
info.deriver = readString(conn->from); info.deriver = readString(conn->from);
if (info.deriver != "") { if (!info.deriver.empty()) {
assertStorePath(info.deriver); assertStorePath(info.deriver);
} }
info.references = readStorePaths<PathSet>(*this, conn->from); info.references = readStorePaths<PathSet>(*this, conn->from);
@ -329,7 +327,7 @@ void RemoteStore::querySubstitutablePathInfos(const PathSet& paths,
Path path = readStorePath(*this, conn->from); Path path = readStorePath(*this, conn->from);
SubstitutablePathInfo& info(infos[path]); SubstitutablePathInfo& info(infos[path]);
info.deriver = readString(conn->from); info.deriver = readString(conn->from);
if (info.deriver != "") { if (!info.deriver.empty()) {
assertStorePath(info.deriver); assertStorePath(info.deriver);
} }
info.references = readStorePaths<PathSet>(*this, conn->from); info.references = readStorePaths<PathSet>(*this, conn->from);
@ -366,7 +364,7 @@ void RemoteStore::queryPathInfoUncached(
info = std::make_shared<ValidPathInfo>(); info = std::make_shared<ValidPathInfo>();
info->path = path; info->path = path;
info->deriver = readString(conn->from); info->deriver = readString(conn->from);
if (info->deriver != "") { if (!info->deriver.empty()) {
assertStorePath(info->deriver); assertStorePath(info->deriver);
} }
info->narHash = Hash(readString(conn->from), htSHA256); info->narHash = Hash(readString(conn->from), htSHA256);
@ -464,7 +462,7 @@ void RemoteStore::addToStore(const ValidPathInfo& info, Source& source,
Path RemoteStore::addToStore(const string& name, const Path& _srcPath, Path RemoteStore::addToStore(const string& name, const Path& _srcPath,
bool recursive, HashType hashAlgo, bool recursive, HashType hashAlgo,
PathFilter& filter, RepairFlag repair) { PathFilter& filter, RepairFlag repair) {
if (repair) { if (repair != 0u) {
throw Error( throw Error(
"repairing is not supported when building through the Nix daemon"); "repairing is not supported when building through the Nix daemon");
} }
@ -506,7 +504,7 @@ Path RemoteStore::addToStore(const string& name, const Path& _srcPath,
Path RemoteStore::addTextToStore(const string& name, const string& s, Path RemoteStore::addTextToStore(const string& name, const string& s,
const PathSet& references, RepairFlag repair) { const PathSet& references, RepairFlag repair) {
if (repair) { if (repair != 0u) {
throw Error( throw Error(
"repairing is not supported when building through the Nix daemon"); "repairing is not supported when building through the Nix daemon");
} }
@ -593,7 +591,7 @@ Roots RemoteStore::findRoots(bool censor) {
conn.processStderr(); conn.processStderr();
auto count = readNum<size_t>(conn->from); auto count = readNum<size_t>(conn->from);
Roots result; Roots result;
while (count--) { while ((count--) != 0u) {
Path link = readString(conn->from); Path link = readString(conn->from);
Path target = readStorePath(*this, conn->from); Path target = readStorePath(*this, conn->from);
result[target].emplace(link); result[target].emplace(link);
@ -605,7 +603,7 @@ void RemoteStore::collectGarbage(const GCOptions& options, GCResults& results) {
auto conn(getConnection()); auto conn(getConnection());
conn->to << wopCollectGarbage << options.action << options.pathsToDelete conn->to << wopCollectGarbage << options.action << options.pathsToDelete
<< options.ignoreLiveness << static_cast<uint64_t>(options.ignoreLiveness)
<< options.maxFreed << options.maxFreed
/* removed options */ /* removed options */
<< 0 << 0 << 0; << 0 << 0 << 0;
@ -631,9 +629,9 @@ void RemoteStore::optimiseStore() {
bool RemoteStore::verifyStore(bool checkContents, RepairFlag repair) { bool RemoteStore::verifyStore(bool checkContents, RepairFlag repair) {
auto conn(getConnection()); auto conn(getConnection());
conn->to << wopVerifyStore << checkContents << repair; conn->to << wopVerifyStore << static_cast<uint64_t>(checkContents) << repair;
conn.processStderr(); conn.processStderr();
return readInt(conn->from); return readInt(conn->from) != 0u;
} }
void RemoteStore::addSignatures(const Path& storePath, const StringSet& sigs) { void RemoteStore::addSignatures(const Path& storePath, const StringSet& sigs) {
@ -694,14 +692,14 @@ std::exception_ptr RemoteStore::Connection::processStderr(Sink* sink,
if (msg == STDERR_WRITE) { if (msg == STDERR_WRITE) {
string s = readString(from); string s = readString(from);
if (!sink) { if (sink == nullptr) {
throw Error("no sink"); throw Error("no sink");
} }
(*sink)(s); (*sink)(s);
} }
else if (msg == STDERR_READ) { else if (msg == STDERR_READ) {
if (!source) { if (source == nullptr) {
throw Error("no source"); throw Error("no source");
} }
auto len = readNum<size_t>(from); auto len = readNum<size_t>(from);

View file

@ -59,7 +59,7 @@ class RemoteStore : public virtual Store {
void querySubstitutablePathInfos(const PathSet& paths, void querySubstitutablePathInfos(const PathSet& paths,
SubstitutablePathInfos& infos) override; SubstitutablePathInfos& infos) override;
void addToStore(const ValidPathInfo& info, Source& nar, RepairFlag repair, void addToStore(const ValidPathInfo& info, Source& source, RepairFlag repair,
CheckSigsFlag checkSigs, CheckSigsFlag checkSigs,
std::shared_ptr<FSAccessor> accessor) override; std::shared_ptr<FSAccessor> accessor) override;

View file

@ -14,7 +14,7 @@ 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) { if (path == nullptr) {
path = "(in-memory)"; path = "(in-memory)";
} }
@ -23,9 +23,8 @@ namespace nix {
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 {
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) {
@ -38,7 +37,7 @@ SQLite::SQLite(const Path& path) {
SQLite::~SQLite() { SQLite::~SQLite() {
try { try {
if (db && sqlite3_close(db) != SQLITE_OK) { if ((db != nullptr) && sqlite3_close(db) != SQLITE_OK) {
throwSQLiteError(db, "closing database"); throwSQLiteError(db, "closing database");
} }
} catch (...) { } catch (...) {
@ -67,7 +66,7 @@ void SQLiteStmt::create(sqlite3* db, const string& sql) {
SQLiteStmt::~SQLiteStmt() { SQLiteStmt::~SQLiteStmt() {
try { try {
if (stmt && sqlite3_finalize(stmt) != SQLITE_OK) { if ((stmt != nullptr) && sqlite3_finalize(stmt) != SQLITE_OK) {
throwSQLiteError(db, fmt("finalizing statement '%s'", sql)); throwSQLiteError(db, fmt("finalizing statement '%s'", sql));
} }
} catch (...) { } catch (...) {

View file

@ -12,7 +12,7 @@ SSHMaster::SSHMaster(const std::string& host, std::string keyFile,
useMaster(useMaster && !fakeSSH), useMaster(useMaster && !fakeSSH),
compress(compress), compress(compress),
logFD(logFD) { logFD(logFD) {
if (host == "" || hasPrefix(host, "-")) { if (host.empty() || hasPrefix(host, "-")) {
throw Error("invalid SSH host name '%s'", host); throw Error("invalid SSH host name '%s'", host);
} }
} }
@ -33,7 +33,8 @@ std::unique_ptr<SSHMaster::Connection> SSHMaster::startCommand(
const std::string& command) { const std::string& command) {
Path socketPath = startMaster(); Path socketPath = startMaster();
Pipe in, out; Pipe in;
Pipe out;
in.create(); in.create();
out.create(); out.create();
@ -63,9 +64,9 @@ std::unique_ptr<SSHMaster::Connection> SSHMaster::startCommand(
if (fakeSSH) { if (fakeSSH) {
args = {"bash", "-c"}; args = {"bash", "-c"};
} else { } else {
args = {"ssh", host.c_str(), "-x", "-a"}; args = {"ssh", host, "-x", "-a"};
addCommonSSHOpts(args); addCommonSSHOpts(args);
if (socketPath != "") { if (!socketPath.empty()) {
args.insert(args.end(), {"-S", socketPath}); args.insert(args.end(), {"-S", socketPath});
} }
// TODO(tazjin): Abseil verbosity flag // TODO(tazjin): Abseil verbosity flag
@ -123,7 +124,7 @@ Path SSHMaster::startMaster() {
throw SysError("duping over stdout"); throw SysError("duping over stdout");
} }
Strings args = {"ssh", host.c_str(), Strings args = {"ssh", host,
"-M", "-N", "-M", "-N",
"-S", state->socketPath, "-S", state->socketPath,
"-o", "LocalCommand=echo started", "-o", "LocalCommand=echo started",

View file

@ -37,9 +37,8 @@ Path Store::toStorePath(const Path& path) const {
Path::size_type slash = path.find('/', storeDir.size() + 1); Path::size_type slash = path.find('/', storeDir.size() + 1);
if (slash == Path::npos) { if (slash == Path::npos) {
return path; return path;
} else {
return Path(path, 0, slash);
} }
return Path(path, 0, slash);
} }
Path Store::followLinksToStore(const Path& _path) const { Path Store::followLinksToStore(const Path& _path) const {
@ -333,7 +332,7 @@ void Store::queryPathInfo(const Path& storePath,
res.first == NarInfoDiskCache::oInvalid ? nullptr : res.second); res.first == NarInfoDiskCache::oInvalid ? nullptr : res.second);
if (res.first == NarInfoDiskCache::oInvalid || if (res.first == NarInfoDiskCache::oInvalid ||
(res.second->path != storePath && (res.second->path != storePath &&
storePathToName(storePath) != "")) { !storePathToName(storePath).empty())) {
throw InvalidPath(format("path '%s' is not valid") % storePath); throw InvalidPath(format("path '%s' is not valid") % storePath);
} }
} }
@ -362,8 +361,8 @@ void Store::queryPathInfo(const Path& storePath,
state_->pathInfoCache.upsert(hashPart, info); state_->pathInfoCache.upsert(hashPart, info);
} }
if (!info || if (!info || (info->path != storePath &&
(info->path != storePath && storePathToName(storePath) != "")) { !storePathToName(storePath).empty())) {
stats.narInfoMissing++; stats.narInfoMissing++;
throw InvalidPath("path '%s' is not valid", storePath); throw InvalidPath("path '%s' is not valid", storePath);
} }
@ -401,7 +400,7 @@ PathSet Store::queryValidPaths(const PathSet& paths,
state->exc = std::current_exception(); state->exc = std::current_exception();
} }
assert(state->left); assert(state->left);
if (!--state->left) { if (--state->left == 0u) {
wakeup.notify_one(); wakeup.notify_one();
} }
}}); }});
@ -415,7 +414,7 @@ PathSet Store::queryValidPaths(const PathSet& paths,
while (true) { while (true) {
auto state(state_.lock()); auto state(state_.lock());
if (!state->left) { if (state->left == 0u) {
if (state->exc) { if (state->exc) {
std::rethrow_exception(state->exc); std::rethrow_exception(state->exc);
} }
@ -430,7 +429,7 @@ PathSet Store::queryValidPaths(const PathSet& paths,
responsibility of the caller to provide a closure. */ responsibility of the caller to provide a closure. */
string Store::makeValidityRegistration(const PathSet& paths, bool showDerivers, string Store::makeValidityRegistration(const PathSet& paths, bool showDerivers,
bool showHash) { bool showHash) {
string s = ""; string s = s;
for (auto& i : paths) { for (auto& i : paths) {
s += i + "\n"; s += i + "\n";
@ -478,7 +477,7 @@ void Store::pathInfoToJSON(JSONPlaceholder& jsonOut, const PathSet& storePaths,
} }
} }
if (info->ca != "") { if (!info->ca.empty()) {
jsonPath.attr("ca", info->ca); jsonPath.attr("ca", info->ca);
} }
@ -490,11 +489,11 @@ void Store::pathInfoToJSON(JSONPlaceholder& jsonOut, const PathSet& storePaths,
} }
if (includeImpureInfo) { if (includeImpureInfo) {
if (info->deriver != "") { if (!info->deriver.empty()) {
jsonPath.attr("deriver", info->deriver); jsonPath.attr("deriver", info->deriver);
} }
if (info->registrationTime) { if (info->registrationTime != 0) {
jsonPath.attr("registrationTime", info->registrationTime); jsonPath.attr("registrationTime", info->registrationTime);
} }
@ -519,7 +518,7 @@ void Store::pathInfoToJSON(JSONPlaceholder& jsonOut, const PathSet& storePaths,
if (narInfo->fileHash) { if (narInfo->fileHash) {
jsonPath.attr("downloadHash", narInfo->fileHash.to_string()); jsonPath.attr("downloadHash", narInfo->fileHash.to_string());
} }
if (narInfo->fileSize) { if (narInfo->fileSize != 0u) {
jsonPath.attr("downloadSize", narInfo->fileSize); jsonPath.attr("downloadSize", narInfo->fileSize);
} }
if (showClosureSize) { if (showClosureSize) {
@ -535,7 +534,8 @@ void Store::pathInfoToJSON(JSONPlaceholder& jsonOut, const PathSet& storePaths,
} }
std::pair<uint64_t, uint64_t> Store::getClosureSize(const Path& storePath) { std::pair<uint64_t, uint64_t> Store::getClosureSize(const Path& storePath) {
uint64_t totalNarSize = 0, totalDownloadSize = 0; uint64_t totalNarSize = 0;
uint64_t totalDownloadSize = 0;
PathSet closure; PathSet closure;
computeFSClosure(storePath, closure, false, false); computeFSClosure(storePath, closure, false, false);
for (auto& p : closure) { for (auto& p : closure) {
@ -596,7 +596,7 @@ void copyStorePath(ref<Store> srcStore, ref<Store> dstStore,
srcStore->narFromPath({storePath}, sink); srcStore->narFromPath({storePath}, sink);
auto info2 = make_ref<ValidPathInfo>(*info); auto info2 = make_ref<ValidPathInfo>(*info);
info2->narHash = hashString(htSHA256, *sink.s); info2->narHash = hashString(htSHA256, *sink.s);
if (!info->narSize) { if (info->narSize == 0u) {
info2->narSize = sink.s->size(); info2->narSize = sink.s->size();
} }
if (info->ultimate) { if (info->ultimate) {
@ -638,7 +638,7 @@ void copyPaths(ref<Store> srcStore, ref<Store> dstStore,
PathSet missing; PathSet missing;
for (auto& path : storePaths) { for (auto& path : storePaths) {
if (!valid.count(path)) { if (valid.count(path) == 0u) {
missing.insert(path); missing.insert(path);
} }
} }
@ -724,7 +724,7 @@ ValidPathInfo decodeValidPathInfo(std::istream& str, bool hashGiven) {
if (!string2Int(s, n)) { if (!string2Int(s, n)) {
throw Error("number expected"); throw Error("number expected");
} }
while (n--) { while ((n--) != 0) {
getline(str, s); getline(str, s);
info.references.insert(s); info.references.insert(s);
} }
@ -737,7 +737,7 @@ ValidPathInfo decodeValidPathInfo(std::istream& str, bool hashGiven) {
string showPaths(const PathSet& paths) { string showPaths(const PathSet& paths) {
string s; string s;
for (auto& i : paths) { for (auto& i : paths) {
if (s.size() != 0) { if (!s.empty()) {
s += ", "; s += ", ";
} }
s += "'" + i + "'"; s += "'" + i + "'";
@ -769,9 +769,9 @@ bool ValidPathInfo::isContentAddressed(const Store& store) const {
Hash hash(std::string(ca, 5)); Hash hash(std::string(ca, 5));
if (store.makeTextPath(storePathToName(path), hash, references) == path) { if (store.makeTextPath(storePathToName(path), hash, references) == path) {
return true; return true;
} else {
warn();
} }
warn();
} }
else if (hasPrefix(ca, "fixed:")) { else if (hasPrefix(ca, "fixed:")) {
@ -781,9 +781,8 @@ bool ValidPathInfo::isContentAddressed(const Store& store) const {
store.makeFixedOutputPath(recursive, hash, storePathToName(path)) == store.makeFixedOutputPath(recursive, hash, storePathToName(path)) ==
path) { path) {
return true; return true;
} else {
warn();
} }
warn();
} }
return false; return false;
@ -900,12 +899,14 @@ ref<Store> openStore(const std::string& uri_,
StoreType getStoreType(const std::string& uri, const std::string& stateDir) { StoreType getStoreType(const std::string& uri, const std::string& stateDir) {
if (uri == "daemon") { if (uri == "daemon") {
return tDaemon; return tDaemon;
} else if (uri == "local" || hasPrefix(uri, "/")) { }
if (uri == "local" || hasPrefix(uri, "/")) {
return tLocal; return tLocal;
} else if (uri == "" || uri == "auto") { } else if (uri.empty() || 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)) { }
if (pathExists(settings.nixDaemonSocketFile)) {
return tDaemon; return tDaemon;
} else { } else {
return tLocal; return tLocal;
@ -940,7 +941,7 @@ std::list<ref<Store>> getDefaultSubstituters() {
StringSet done; StringSet done;
auto addStore = [&](const std::string& uri) { auto addStore = [&](const std::string& uri) {
if (done.count(uri)) { if (done.count(uri) != 0u) {
return; return;
} }
done.insert(uri); done.insert(uri);

View file

@ -533,12 +533,12 @@ class Store : public std::enable_shared_from_this<Store>, public Config {
`storePath' is returned; that is, the closures under the `storePath' is returned; that is, the closures under the
`referrers' relation instead of the `references' relation is `referrers' relation instead of the `references' relation is
returned. */ returned. */
virtual void computeFSClosure(const PathSet& paths, PathSet& out, virtual void computeFSClosure(const PathSet& paths, PathSet& paths_,
bool flipDirection = false, bool flipDirection = false,
bool includeOutputs = false, bool includeOutputs = false,
bool includeDerivers = false); bool includeDerivers = false);
void computeFSClosure(const Path& path, PathSet& out, void computeFSClosure(const Path& path, PathSet& paths_,
bool flipDirection = false, bool includeOutputs = false, bool flipDirection = false, bool includeOutputs = false,
bool includeDerivers = false); bool includeDerivers = false);

View file

@ -40,7 +40,7 @@ const std::string narVersionMagic1 = "nix-archive-1";
static string caseHackSuffix = "~nix~case~hack~"; static string caseHackSuffix = "~nix~case~hack~";
PathFilter defaultPathFilter = [](const Path&) { return true; }; PathFilter defaultPathFilter = [](const Path& /*unused*/) { return true; };
static void dumpContents(const Path& path, size_t size, Sink& sink) { static void dumpContents(const Path& path, size_t size, Sink& sink) {
sink << "contents" << size; sink << "contents" << size;
@ -67,7 +67,7 @@ static void dump(const Path& path, Sink& sink, PathFilter& filter) {
checkInterrupt(); checkInterrupt();
struct stat st; struct stat st;
if (lstat(path.c_str(), &st)) { if (lstat(path.c_str(), &st) != 0) {
throw SysError(format("getting attributes of path '%1%'") % path); throw SysError(format("getting attributes of path '%1%'") % path);
} }
@ -76,7 +76,7 @@ static void dump(const Path& path, Sink& sink, PathFilter& filter) {
if (S_ISREG(st.st_mode)) { if (S_ISREG(st.st_mode)) {
sink << "type" sink << "type"
<< "regular"; << "regular";
if (st.st_mode & S_IXUSR) { if ((st.st_mode & S_IXUSR) != 0u) {
sink << "executable" sink << "executable"
<< ""; << "";
} }
@ -167,7 +167,7 @@ static void parseContents(ParseSink& sink, Source& source, const Path& path) {
unsigned long long left = size; unsigned long long left = size;
std::vector<unsigned char> buf(65536); std::vector<unsigned char> buf(65536);
while (left) { while (left != 0u) {
checkInterrupt(); checkInterrupt();
auto n = buf.size(); auto n = buf.size();
if ((unsigned long long)n > left) { if ((unsigned long long)n > left) {
@ -208,7 +208,7 @@ static void parse(ParseSink& sink, Source& source, const Path& path) {
break; break;
} }
else if (s == "type") { if (s == "type") {
if (type != tpUnknown) { if (type != tpUnknown) {
throw badArchive("multiple type fields"); throw badArchive("multiple type fields");
} }
@ -240,14 +240,15 @@ static void parse(ParseSink& sink, Source& source, const Path& path) {
else if (s == "executable" && type == tpRegular) { else if (s == "executable" && type == tpRegular) {
auto s = readString(source); auto s = readString(source);
if (s != "") { if (!s.empty()) {
throw badArchive("executable marker has non-empty value"); throw badArchive("executable marker has non-empty value");
} }
sink.isExecutable(); sink.isExecutable();
} }
else if (s == "entry" && type == tpDirectory) { else if (s == "entry" && type == tpDirectory) {
string name, prevName; string name;
string prevName;
s = readString(source); s = readString(source);
if (s != "(") { if (s != "(") {
@ -261,7 +262,8 @@ static void parse(ParseSink& sink, Source& source, const Path& path) {
if (s == ")") { if (s == ")") {
break; break;
} else if (s == "name") { }
if (s == "name") {
name = readString(source); name = readString(source);
if (name.empty() || name == "." || name == ".." || if (name.empty() || name == "." || name == ".." ||
name.find('/') != string::npos || name.find('/') != string::npos ||
@ -350,7 +352,7 @@ struct RestoreSink : ParseSink {
void preallocateContents(unsigned long long len) override { void preallocateContents(unsigned long long len) override {
#if HAVE_POSIX_FALLOCATE #if HAVE_POSIX_FALLOCATE
if (len) { if (len != 0u) {
errno = posix_fallocate(fd.get(), 0, len); errno = posix_fallocate(fd.get(), 0, len);
/* Note that EINVAL may indicate that the underlying /* Note that EINVAL may indicate that the underlying
filesystem doesn't support preallocation (e.g. on filesystem doesn't support preallocation (e.g. on

View file

@ -7,9 +7,9 @@ namespace nix {
Args::FlagMaker Args::mkFlag() { return FlagMaker(*this); } Args::FlagMaker Args::mkFlag() { return FlagMaker(*this); }
Args::FlagMaker::~FlagMaker() { Args::FlagMaker::~FlagMaker() {
assert(flag->longName != ""); assert(!flag->longName.empty());
args.longFlags[flag->longName] = flag; args.longFlags[flag->longName] = flag;
if (flag->shortName) { if (flag->shortName != 0) {
args.shortFlags[flag->shortName] = flag; args.shortFlags[flag->shortName] = flag;
} }
} }
@ -26,12 +26,12 @@ void Args::parseCmdline(const Strings& _cmdline) {
/* Expand compound dash options (i.e., `-qlf' -> `-q -l -f', /* Expand compound dash options (i.e., `-qlf' -> `-q -l -f',
`-j3` -> `-j 3`). */ `-j3` -> `-j 3`). */
if (!dashDash && arg.length() > 2 && arg[0] == '-' && arg[1] != '-' && if (!dashDash && arg.length() > 2 && arg[0] == '-' && arg[1] != '-' &&
isalpha(arg[1])) { (isalpha(arg[1]) != 0)) {
*pos = (string) "-" + arg[1]; *pos = (string) "-" + arg[1];
auto next = pos; auto next = pos;
++next; ++next;
for (unsigned int j = 2; j < arg.length(); j++) { for (unsigned int j = 2; j < arg.length(); j++) {
if (isalpha(arg[j])) { if (isalpha(arg[j]) != 0) {
cmdline.insert(next, (string) "-" + arg[j]); cmdline.insert(next, (string) "-" + arg[j]);
} else { } else {
cmdline.insert(next, string(arg, j)); cmdline.insert(next, string(arg, j));
@ -74,11 +74,11 @@ void Args::printHelp(const string& programName, std::ostream& out) {
std::cout << "\n"; std::cout << "\n";
auto s = description(); auto s = description();
if (s != "") { if (!s.empty()) {
std::cout << "\nSummary: " << s << ".\n"; std::cout << "\nSummary: " << s << ".\n";
} }
if (longFlags.size()) { if (!longFlags.empty() != 0u) {
std::cout << "\n"; std::cout << "\n";
std::cout << "Flags:\n"; std::cout << "Flags:\n";
printFlags(out); printFlags(out);
@ -88,11 +88,11 @@ void Args::printHelp(const string& programName, std::ostream& out) {
void Args::printFlags(std::ostream& out) { void Args::printFlags(std::ostream& out) {
Table2 table; Table2 table;
for (auto& flag : longFlags) { for (auto& flag : longFlags) {
if (hiddenCategories.count(flag.second->category)) { if (hiddenCategories.count(flag.second->category) != 0u) {
continue; continue;
} }
table.push_back(std::make_pair( table.push_back(std::make_pair(
(flag.second->shortName (flag.second->shortName != 0
? std::string("-") + flag.second->shortName + ", " ? std::string("-") + flag.second->shortName + ", "
: " ") + : " ") +
"--" + flag.first + renderLabels(flag.second->labels), "--" + flag.first + renderLabels(flag.second->labels),
@ -188,7 +188,7 @@ Strings argvToStrings(int argc, char** argv) {
Strings args; Strings args;
argc--; argc--;
argv++; argv++;
while (argc--) { while ((argc--) != 0) {
args.push_back(*argv++); args.push_back(*argv++);
} }
return args; return args;

View file

@ -21,7 +21,7 @@ struct ChunkedCompressionSink : CompressionSink {
void write(const unsigned char* data, size_t len) override { void write(const unsigned char* data, size_t len) override {
const size_t CHUNK_SIZE = sizeof(outbuf) << 2; const size_t CHUNK_SIZE = sizeof(outbuf) << 2;
while (len) { while (len != 0u) {
size_t n = std::min(CHUNK_SIZE, len); size_t n = std::min(CHUNK_SIZE, len);
writeInternal(data, n); writeInternal(data, n);
data += n; data += n;
@ -68,10 +68,10 @@ struct XzDecompressionSink : CompressionSink {
strm.next_in = data; strm.next_in = data;
strm.avail_in = len; strm.avail_in = len;
while (!finished && (!data || strm.avail_in)) { while (!finished && ((data == nullptr) || (strm.avail_in != 0u))) {
checkInterrupt(); checkInterrupt();
lzma_ret ret = lzma_code(&strm, data ? LZMA_RUN : LZMA_FINISH); lzma_ret ret = lzma_code(&strm, data != nullptr ? LZMA_RUN : LZMA_FINISH);
if (ret != LZMA_OK && ret != LZMA_STREAM_END) { if (ret != LZMA_OK && ret != LZMA_STREAM_END) {
throw CompressionError("error %d while decompressing xz file", ret); throw CompressionError("error %d while decompressing xz file", ret);
} }
@ -116,7 +116,7 @@ struct BzipDecompressionSink : ChunkedCompressionSink {
strm.next_in = (char*)data; strm.next_in = (char*)data;
strm.avail_in = len; strm.avail_in = len;
while (strm.avail_in) { while (strm.avail_in != 0u) {
checkInterrupt(); checkInterrupt();
int ret = BZ2_bzDecompress(&strm); int ret = BZ2_bzDecompress(&strm);
@ -142,7 +142,7 @@ struct BrotliDecompressionSink : ChunkedCompressionSink {
explicit BrotliDecompressionSink(Sink& nextSink) : nextSink(nextSink) { explicit BrotliDecompressionSink(Sink& nextSink) : nextSink(nextSink) {
state = BrotliDecoderCreateInstance(nullptr, nullptr, nullptr); state = BrotliDecoderCreateInstance(nullptr, nullptr, nullptr);
if (!state) { if (state == nullptr) {
throw CompressionError("unable to initialize brotli decoder"); throw CompressionError("unable to initialize brotli decoder");
} }
} }
@ -160,11 +160,11 @@ struct BrotliDecompressionSink : ChunkedCompressionSink {
uint8_t* next_out = outbuf; uint8_t* next_out = outbuf;
size_t avail_out = sizeof(outbuf); size_t avail_out = sizeof(outbuf);
while (!finished && (!data || avail_in)) { while (!finished && ((data == nullptr) || (avail_in != 0u))) {
checkInterrupt(); checkInterrupt();
if (!BrotliDecoderDecompressStream(state, &avail_in, &next_in, &avail_out, if (BrotliDecoderDecompressStream(state, &avail_in, &next_in, &avail_out,
&next_out, nullptr)) { &next_out, nullptr) == 0u) {
throw CompressionError("error while decompressing brotli file"); throw CompressionError("error while decompressing brotli file");
} }
@ -174,7 +174,7 @@ struct BrotliDecompressionSink : ChunkedCompressionSink {
avail_out = sizeof(outbuf); avail_out = sizeof(outbuf);
} }
finished = BrotliDecoderIsFinished(state); finished = (BrotliDecoderIsFinished(state) != 0);
} }
} }
}; };
@ -189,9 +189,10 @@ ref<std::string> decompress(const std::string& method, const std::string& in) {
ref<CompressionSink> makeDecompressionSink(const std::string& method, ref<CompressionSink> makeDecompressionSink(const std::string& method,
Sink& nextSink) { Sink& nextSink) {
if (method == "none" || method == "") { if (method == "none" || method.empty()) {
return make_ref<NoneSink>(nextSink); return make_ref<NoneSink>(nextSink);
} else if (method == "xz") { }
if (method == "xz") {
return make_ref<XzDecompressionSink>(nextSink); return make_ref<XzDecompressionSink>(nextSink);
} else if (method == "bzip2") { } else if (method == "bzip2") {
return make_ref<BzipDecompressionSink>(nextSink); return make_ref<BzipDecompressionSink>(nextSink);
@ -260,10 +261,10 @@ struct XzCompressionSink : CompressionSink {
strm.next_in = data; strm.next_in = data;
strm.avail_in = len; strm.avail_in = len;
while (!finished && (!data || strm.avail_in)) { while (!finished && ((data == nullptr) || (strm.avail_in != 0u))) {
checkInterrupt(); checkInterrupt();
lzma_ret ret = lzma_code(&strm, data ? LZMA_RUN : LZMA_FINISH); lzma_ret ret = lzma_code(&strm, data != nullptr ? LZMA_RUN : LZMA_FINISH);
if (ret != LZMA_OK && ret != LZMA_STREAM_END) { if (ret != LZMA_OK && ret != LZMA_STREAM_END) {
throw CompressionError("error %d while compressing xz file", ret); throw CompressionError("error %d while compressing xz file", ret);
} }
@ -308,10 +309,10 @@ struct BzipCompressionSink : ChunkedCompressionSink {
strm.next_in = (char*)data; strm.next_in = (char*)data;
strm.avail_in = len; strm.avail_in = len;
while (!finished && (!data || strm.avail_in)) { while (!finished && ((data == nullptr) || (strm.avail_in != 0u))) {
checkInterrupt(); checkInterrupt();
int ret = BZ2_bzCompress(&strm, data ? BZ_RUN : BZ_FINISH); int ret = BZ2_bzCompress(&strm, data != nullptr ? BZ_RUN : BZ_FINISH);
if (ret != BZ_RUN_OK && ret != BZ_FINISH_OK && ret != BZ_STREAM_END) { if (ret != BZ_RUN_OK && ret != BZ_FINISH_OK && ret != BZ_STREAM_END) {
throw CompressionError("error %d while compressing bzip2 file", ret); throw CompressionError("error %d while compressing bzip2 file", ret);
} }
@ -335,7 +336,7 @@ struct BrotliCompressionSink : ChunkedCompressionSink {
explicit BrotliCompressionSink(Sink& nextSink) : nextSink(nextSink) { explicit BrotliCompressionSink(Sink& nextSink) : nextSink(nextSink) {
state = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr); state = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
if (!state) { if (state == nullptr) {
throw CompressionError("unable to initialise brotli encoder"); throw CompressionError("unable to initialise brotli encoder");
} }
} }
@ -353,12 +354,14 @@ struct BrotliCompressionSink : ChunkedCompressionSink {
uint8_t* next_out = outbuf; uint8_t* next_out = outbuf;
size_t avail_out = sizeof(outbuf); size_t avail_out = sizeof(outbuf);
while (!finished && (!data || avail_in)) { while (!finished && ((data == nullptr) || (avail_in != 0u))) {
checkInterrupt(); checkInterrupt();
if (!BrotliEncoderCompressStream( if (BrotliEncoderCompressStream(state,
state, data ? BROTLI_OPERATION_PROCESS : BROTLI_OPERATION_FINISH, data != nullptr ? BROTLI_OPERATION_PROCESS
&avail_in, &next_in, &avail_out, &next_out, nullptr)) { : BROTLI_OPERATION_FINISH,
&avail_in, &next_in, &avail_out,
&next_out, nullptr) == 0) {
throw CompressionError("error while compressing brotli compression"); throw CompressionError("error while compressing brotli compression");
} }
@ -368,7 +371,7 @@ struct BrotliCompressionSink : ChunkedCompressionSink {
avail_out = sizeof(outbuf); avail_out = sizeof(outbuf);
} }
finished = BrotliEncoderIsFinished(state); finished = (BrotliEncoderIsFinished(state) != 0);
} }
} }
}; };
@ -377,7 +380,8 @@ ref<CompressionSink> makeCompressionSink(const std::string& method,
Sink& nextSink, const bool parallel) { Sink& nextSink, const bool parallel) {
if (method == "none") { if (method == "none") {
return make_ref<NoneSink>(nextSink); return make_ref<NoneSink>(nextSink);
} else if (method == "xz") { }
if (method == "xz") {
return make_ref<XzCompressionSink>(nextSink, parallel); return make_ref<XzCompressionSink>(nextSink, parallel);
} else if (method == "bzip2") { } else if (method == "bzip2") {
return make_ref<BzipCompressionSink>(nextSink); return make_ref<BzipCompressionSink>(nextSink);

View file

@ -303,7 +303,7 @@ template class BaseSetting<Strings>;
template class BaseSetting<StringSet>; template class BaseSetting<StringSet>;
void PathSetting::set(const std::string& str) { void PathSetting::set(const std::string& str) {
if (str == "") { if (str.empty()) {
if (allowEmpty) { if (allowEmpty) {
value = ""; value = "";
} else { } else {
@ -356,7 +356,7 @@ GlobalConfig globalConfig;
GlobalConfig::ConfigRegistrations* GlobalConfig::configRegistrations; GlobalConfig::ConfigRegistrations* GlobalConfig::configRegistrations;
GlobalConfig::Register::Register(Config* config) { GlobalConfig::Register::Register(Config* config) {
if (!configRegistrations) { if (configRegistrations == nullptr) {
configRegistrations = new ConfigRegistrations; configRegistrations = new ConfigRegistrations;
} }
configRegistrations->emplace_back(config); configRegistrations->emplace_back(config);

View file

@ -193,7 +193,7 @@ Hash::Hash(const std::string& s, HashType type) : type(type) {
if (i < hashSize - 1) { if (i < hashSize - 1) {
hash[i + 1] |= digit >> (8 - j); hash[i + 1] |= digit >> (8 - j);
} else { } else {
if (digit >> (8 - j)) { if ((digit >> (8 - j)) != 0) {
throw BadHash("invalid base-32 hash '%s'", s); throw BadHash("invalid base-32 hash '%s'", s);
} }
} }
@ -280,7 +280,7 @@ Hash hashFile(HashType ht, const Path& path) {
std::vector<unsigned char> buf(8192); std::vector<unsigned char> buf(8192);
ssize_t n; ssize_t n;
while ((n = read(fd.get(), buf.data(), buf.size()))) { while ((n = read(fd.get(), buf.data(), buf.size())) != 0) {
checkInterrupt(); checkInterrupt();
if (n == -1) { if (n == -1) {
throw SysError(format("reading file '%1%'") % path); throw SysError(format("reading file '%1%'") % path);
@ -341,7 +341,8 @@ Hash compressHash(const Hash& hash, unsigned int newSize) {
HashType parseHashType(const string& s) { HashType parseHashType(const string& s) {
if (s == "md5") { if (s == "md5") {
return htMD5; return htMD5;
} else if (s == "sha1") { }
if (s == "sha1") {
return htSHA1; return htSHA1;
} else if (s == "sha256") { } else if (s == "sha256") {
return htSHA256; return htSHA256;
@ -355,7 +356,8 @@ HashType parseHashType(const string& s) {
string printHashType(HashType ht) { string printHashType(HashType ht) {
if (ht == htMD5) { if (ht == htMD5) {
return "md5"; return "md5";
} else if (ht == htSHA1) { }
if (ht == htSHA1) {
return "sha1"; return "sha1";
} else if (ht == htSHA256) { } else if (ht == htSHA256) {
return "sha256"; return "sha256";

View file

@ -27,7 +27,7 @@ void toJSON(std::ostream& str, const char* start, const char* end) {
} }
void toJSON(std::ostream& str, const char* s) { void toJSON(std::ostream& str, const char* s) {
if (!s) { if (s == nullptr) {
str << "null"; str << "null";
} else { } else {
toJSON(str, s, s + strlen(s)); toJSON(str, s, s + strlen(s));
@ -91,7 +91,7 @@ JSONWriter::JSONWriter(std::ostream& str, bool indent)
JSONWriter::JSONWriter(JSONState* state) : state(state) { state->stack++; } JSONWriter::JSONWriter(JSONState* state) : state(state) { state->stack++; }
JSONWriter::~JSONWriter() { JSONWriter::~JSONWriter() {
if (state) { if (state != nullptr) {
assertActive(); assertActive();
state->stack--; state->stack--;
if (state->stack == 0) { if (state->stack == 0) {
@ -150,7 +150,7 @@ void JSONObject::open() {
} }
JSONObject::~JSONObject() { JSONObject::~JSONObject() {
if (state) { if (state != nullptr) {
state->depth--; state->depth--;
if (state->indent && !first) { if (state->indent && !first) {
indent(); indent();

View file

@ -16,7 +16,7 @@ void BufferedSink::operator()(const unsigned char* data, size_t len) {
buffer = decltype(buffer)(new unsigned char[bufSize]); buffer = decltype(buffer)(new unsigned char[bufSize]);
} }
while (len) { while (len != 0u) {
/* Optimisation: bypass the buffer if the data exceeds the /* Optimisation: bypass the buffer if the data exceeds the
buffer size. */ buffer size. */
if (bufPos + len >= bufSize) { if (bufPos + len >= bufSize) {
@ -81,7 +81,7 @@ void FdSink::write(const unsigned char* data, size_t len) {
bool FdSink::good() { return _good; } bool FdSink::good() { return _good; }
void Source::operator()(unsigned char* data, size_t len) { void Source::operator()(unsigned char* data, size_t len) {
while (len) { while (len != 0u) {
size_t n = read(data, len); size_t n = read(data, len);
data += n; data += n;
len -= n; len -= n;
@ -108,7 +108,7 @@ size_t BufferedSource::read(unsigned char* data, size_t len) {
buffer = decltype(buffer)(new unsigned char[bufSize]); buffer = decltype(buffer)(new unsigned char[bufSize]);
} }
if (!bufPosIn) { if (bufPosIn == 0u) {
bufPosIn = readUnbuffered(buffer.get(), bufSize); bufPosIn = readUnbuffered(buffer.get(), bufSize);
} }
@ -177,7 +177,7 @@ std::unique_ptr<Source> sinkToSource(std::function<void(Sink&)> fun,
if (!coro) { if (!coro) {
coro = coro_t::pull_type([&](coro_t::push_type& yield) { coro = coro_t::pull_type([&](coro_t::push_type& yield) {
LambdaSink sink([&](const unsigned char* data, size_t len) { LambdaSink sink([&](const unsigned char* data, size_t len) {
if (len) { if (len != 0u) {
yield(std::string((const char*)data, len)); yield(std::string((const char*)data, len));
} }
}); });
@ -210,7 +210,7 @@ std::unique_ptr<Source> sinkToSource(std::function<void(Sink&)> fun,
} }
void writePadding(size_t len, Sink& sink) { void writePadding(size_t len, Sink& sink) {
if (len % 8) { if ((len % 8) != 0u) {
unsigned char zero[8]; unsigned char zero[8];
memset(zero, 0, sizeof(zero)); memset(zero, 0, sizeof(zero));
sink(zero, 8 - (len % 8)); sink(zero, 8 - (len % 8));
@ -247,12 +247,12 @@ Sink& operator<<(Sink& sink, const StringSet& s) {
} }
void readPadding(size_t len, Source& source) { void readPadding(size_t len, Source& source) {
if (len % 8) { if ((len % 8) != 0u) {
unsigned char zero[8]; unsigned char zero[8];
size_t n = 8 - (len % 8); size_t n = 8 - (len % 8);
source(zero, n); source(zero, n);
for (unsigned int i = 0; i < n; i++) { for (unsigned int i = 0; i < n; i++) {
if (zero[i]) { if (zero[i] != 0u) {
throw SerialisationError("non-zero padding"); throw SerialisationError("non-zero padding");
} }
} }

View file

@ -8,9 +8,9 @@ namespace nix {
ThreadPool::ThreadPool(size_t _maxThreads) : maxThreads(_maxThreads) { ThreadPool::ThreadPool(size_t _maxThreads) : maxThreads(_maxThreads) {
restoreAffinity(); // FIXME restoreAffinity(); // FIXME
if (!maxThreads) { if (maxThreads == 0u) {
maxThreads = std::thread::hardware_concurrency(); maxThreads = std::thread::hardware_concurrency();
if (!maxThreads) { if (maxThreads == 0u) {
maxThreads = 1; maxThreads = 1;
} }
} }
@ -111,8 +111,8 @@ void ThreadPool::doWork(bool mainThread) {
try { try {
std::rethrow_exception(exc); std::rethrow_exception(exc);
} catch (std::exception& e) { } catch (std::exception& e) {
if (!dynamic_cast<Interrupted*>(&e) && if ((dynamic_cast<Interrupted*>(&e) == nullptr) &&
!dynamic_cast<ThreadPoolShutDown*>(&e)) { (dynamic_cast<ThreadPoolShutDown*>(&e) == nullptr)) {
ignoreException(); ignoreException();
} }
} catch (...) { } catch (...) {
@ -135,7 +135,7 @@ void ThreadPool::doWork(bool mainThread) {
/* If there are no active or pending items, and the /* If there are no active or pending items, and the
main thread is running process(), then no new items main thread is running process(), then no new items
can be added. So exit. */ can be added. So exit. */
if (!state->active && state->draining) { if ((state->active == 0u) && state->draining) {
quit = true; quit = true;
work.notify_all(); work.notify_all();
return; return;

View file

@ -35,7 +35,7 @@
#include <sys/prctl.h> #include <sys/prctl.h>
#endif #endif
extern char** environ __attribute__((weak)); __attribute__((weak));
namespace nix { namespace nix {
@ -53,15 +53,15 @@ std::string SysError::addErrno(const std::string& s) {
string getEnv(const string& key, const string& def) { string getEnv(const string& key, const string& def) {
char* value = getenv(key.c_str()); char* value = getenv(key.c_str());
return value ? string(value) : def; return value != nullptr ? string(value) : def;
} }
std::map<std::string, std::string> getEnv() { std::map<std::string, std::string> getEnv() {
std::map<std::string, std::string> env; std::map<std::string, std::string> env;
for (size_t i = 0; environ[i]; ++i) { for (size_t i = 0; environ[i] != nullptr; ++i) {
auto s = environ[i]; auto s = environ[i];
auto eq = strchr(s, '='); auto eq = strchr(s, '=');
if (!eq) { if (eq == nullptr) {
// invalid env, just keep going // invalid env, just keep going
continue; continue;
} }
@ -85,7 +85,7 @@ void replaceEnv(std::map<std::string, std::string> newEnv) {
Path absPath(Path path, Path dir) { Path absPath(Path path, Path dir) {
if (path[0] != '/') { if (path[0] != '/') {
if (dir == "") { if (dir.empty()) {
#ifdef __GNU__ #ifdef __GNU__
/* GNU (aka. GNU/Hurd) doesn't have any limitation on path /* GNU (aka. GNU/Hurd) doesn't have any limitation on path
lengths and doesn't define `PATH_MAX'. */ lengths and doesn't define `PATH_MAX'. */
@ -93,7 +93,7 @@ Path absPath(Path path, Path dir) {
if (buf == NULL) if (buf == NULL)
#else #else
char buf[PATH_MAX]; char buf[PATH_MAX];
if (!getcwd(buf, sizeof(buf))) { if (getcwd(buf, sizeof(buf)) == nullptr) {
#endif #endif
throw SysError("cannot get cwd"); throw SysError("cannot get cwd");
} }
@ -108,7 +108,7 @@ return canonPath(path);
} // namespace nix } // namespace nix
Path canonPath(const Path& path, bool resolveSymlinks) { Path canonPath(const Path& path, bool resolveSymlinks) {
assert(path != ""); assert(!path.empty());
string s; string s;
@ -116,12 +116,14 @@ Path canonPath(const Path& path, bool resolveSymlinks) {
throw Error(format("not an absolute path: '%1%'") % path); throw Error(format("not an absolute path: '%1%'") % path);
} }
string::const_iterator i = path.begin(), end = path.end(); string::const_iterator i = path.begin();
string::const_iterator end = path.end();
string temp; string temp;
/* Count the number of times we follow a symlink and stop at some /* Count the number of times we follow a symlink and stop at some
arbitrary (but high) limit to prevent infinite loops. */ arbitrary (but high) limit to prevent infinite loops. */
unsigned int followCount = 0, maxFollow = 1024; unsigned int followCount = 0;
unsigned int maxFollow = 1024;
while (true) { while (true) {
/* Skip slashes. */ /* Skip slashes. */
@ -210,7 +212,7 @@ bool isDirOrInDir(const Path& path, const Path& dir) {
struct stat lstat(const Path& path) { struct stat lstat(const Path& path) {
struct stat st; struct stat st;
if (lstat(path.c_str(), &st)) { if (lstat(path.c_str(), &st) != 0) {
throw SysError(format("getting status of '%1%'") % path); throw SysError(format("getting status of '%1%'") % path);
} }
return st; return st;
@ -220,7 +222,7 @@ 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) { if (res == 0) {
return true; return true;
} }
if (errno != ENOENT && errno != ENOTDIR) { if (errno != ENOENT && errno != ENOTDIR) {
@ -238,9 +240,9 @@ Path readLink(const Path& path) {
if (rlSize == -1) { if (rlSize == -1) {
if (errno == EINVAL) { if (errno == EINVAL) {
throw Error("'%1%' is not a symlink", path); throw Error("'%1%' is not a symlink", path);
} else {
throw SysError("reading symbolic link '%1%'", path);
} }
throw SysError("reading symbolic link '%1%'", path);
} else if (rlSize < bufSize) { } else if (rlSize < bufSize) {
return string(buf.data(), rlSize); return string(buf.data(), rlSize);
} }
@ -436,9 +438,8 @@ static Path tempName(Path tmpRoot, const Path& prefix, bool includePid,
if (includePid) { if (includePid) {
return (format("%1%/%2%-%3%-%4%") % tmpRoot % prefix % getpid() % counter++) return (format("%1%/%2%-%3%-%4%") % tmpRoot % prefix % getpid() % counter++)
.str(); .str();
} else {
return (format("%1%/%2%-%3%") % tmpRoot % prefix % counter++).str();
} }
return (format("%1%/%2%-%3%") % tmpRoot % prefix % counter++).str();
} }
Path createTempDir(const Path& tmpRoot, const Path& prefix, bool includePid, Path createTempDir(const Path& tmpRoot, const Path& prefix, bool includePid,
@ -473,7 +474,7 @@ Path createTempDir(const Path& tmpRoot, const Path& prefix, bool includePid,
std::string getUserName() { std::string getUserName() {
auto pw = getpwuid(geteuid()); auto pw = getpwuid(geteuid());
std::string name = pw ? pw->pw_name : getEnv("USER", ""); std::string name = pw != nullptr ? pw->pw_name : getEnv("USER", "");
if (name.empty()) { if (name.empty()) {
throw Error("cannot figure out user name"); throw Error("cannot figure out user name");
} }
@ -487,7 +488,7 @@ static Lazy<Path> getHome2([]() {
struct passwd pwbuf; struct passwd pwbuf;
struct passwd* pw; struct passwd* pw;
if (getpwuid_r(geteuid(), &pwbuf, buf.data(), buf.size(), &pw) != 0 || if (getpwuid_r(geteuid(), &pwbuf, buf.data(), buf.size(), &pw) != 0 ||
!pw || !pw->pw_dir || !pw->pw_dir[0]) { (pw == nullptr) || (pw->pw_dir == nullptr) || (pw->pw_dir[0] == 0)) {
throw Error("cannot determine user's home directory"); throw Error("cannot determine user's home directory");
} }
homeDir = pw->pw_dir; homeDir = pw->pw_dir;
@ -557,7 +558,7 @@ Paths createDirs(const Path& path) {
} }
void createSymlink(const Path& target, const Path& link) { void createSymlink(const Path& target, const Path& link) {
if (symlink(target.c_str(), link.c_str())) { if (symlink(target.c_str(), link.c_str()) != 0) {
throw SysError(format("creating symlink from '%1%' to '%2%'") % link % throw SysError(format("creating symlink from '%1%' to '%2%'") % link %
target); target);
} }
@ -585,7 +586,7 @@ void replaceSymlink(const Path& target, const Path& link) {
} }
void readFull(int fd, unsigned char* buf, size_t count) { void readFull(int fd, unsigned char* buf, size_t count) {
while (count) { while (count != 0u) {
checkInterrupt(); checkInterrupt();
ssize_t res = read(fd, (char*)buf, count); ssize_t res = read(fd, (char*)buf, count);
if (res == -1) { if (res == -1) {
@ -604,7 +605,7 @@ void readFull(int fd, unsigned char* buf, size_t count) {
void writeFull(int fd, const unsigned char* buf, size_t count, void writeFull(int fd, const unsigned char* buf, size_t count,
bool allowInterrupts) { bool allowInterrupts) {
while (count) { while (count != 0u) {
if (allowInterrupts) { if (allowInterrupts) {
checkInterrupt(); checkInterrupt();
} }
@ -989,11 +990,12 @@ void runProgram2(const RunOptions& options) {
} }
/* Create a pipe. */ /* Create a pipe. */
Pipe out, in; Pipe out;
if (options.standardOut) { Pipe in;
if (options.standardOut != nullptr) {
out.create(); out.create();
} }
if (source) { if (source != nullptr) {
in.create(); in.create();
} }
@ -1011,7 +1013,7 @@ void runProgram2(const RunOptions& options) {
if (options.environment) { if (options.environment) {
replaceEnv(*options.environment); replaceEnv(*options.environment);
} }
if (options.standardOut && if ((options.standardOut != nullptr) &&
dup2(out.writeSide.get(), STDOUT_FILENO) == -1) { dup2(out.writeSide.get(), STDOUT_FILENO) == -1) {
throw SysError("dupping stdout"); throw SysError("dupping stdout");
} }
@ -1020,7 +1022,8 @@ void runProgram2(const RunOptions& options) {
throw SysError("cannot dup stdout into stderr"); throw SysError("cannot dup stdout into stderr");
} }
} }
if (source && dup2(in.readSide.get(), STDIN_FILENO) == -1) { if ((source != nullptr) &&
dup2(in.readSide.get(), STDIN_FILENO) == -1) {
throw SysError("dupping stdin"); throw SysError("dupping stdin");
} }
@ -1065,7 +1068,7 @@ void runProgram2(const RunOptions& options) {
} }
}); });
if (source) { if (source != nullptr) {
in.readSide = -1; in.readSide = -1;
writerThread = std::thread([&]() { writerThread = std::thread([&]() {
try { try {
@ -1087,7 +1090,7 @@ void runProgram2(const RunOptions& options) {
}); });
} }
if (options.standardOut) { if (options.standardOut != nullptr) {
drainFD(out.readSide.get(), *options.standardOut); drainFD(out.readSide.get(), *options.standardOut);
} }
@ -1095,11 +1098,11 @@ void runProgram2(const RunOptions& options) {
int status = pid.wait(); int status = pid.wait();
/* Wait for the writer thread to finish. */ /* Wait for the writer thread to finish. */
if (source) { if (source != nullptr) {
promise.get_future().get(); promise.get_future().get();
} }
if (status) { if (status != 0) {
throw ExecError(status, fmt("program '%1%' %2%", options.program, throw ExecError(status, fmt("program '%1%' %2%", options.program,
statusToString(status))); statusToString(status)));
} }
@ -1110,7 +1113,7 @@ void closeMostFDs(const set<int>& exceptions) {
try { try {
for (auto& s : readDirectory("/proc/self/fd")) { for (auto& s : readDirectory("/proc/self/fd")) {
auto fd = std::stoi(s.name); auto fd = std::stoi(s.name);
if (!exceptions.count(fd)) { if (exceptions.count(fd) == 0u) {
DLOG(INFO) << "closing leaked FD " << fd; DLOG(INFO) << "closing leaked FD " << fd;
close(fd); close(fd);
} }
@ -1123,7 +1126,7 @@ void closeMostFDs(const set<int>& exceptions) {
int maxFD = 0; int maxFD = 0;
maxFD = sysconf(_SC_OPEN_MAX); maxFD = sysconf(_SC_OPEN_MAX);
for (int fd = 0; fd < maxFD; ++fd) { for (int fd = 0; fd < maxFD; ++fd) {
if (!exceptions.count(fd)) { if (exceptions.count(fd) == 0u) {
close(fd); close(fd);
} /* ignore result */ } /* ignore result */
} }
@ -1150,7 +1153,7 @@ void _interrupted() {
/* Block user interrupts while an exception is being handled. /* Block user interrupts while an exception is being handled.
Throwing an exception while another exception is being handled Throwing an exception while another exception is being handled
kills the program! */ kills the program! */
if (!interruptThrown && !std::uncaught_exceptions()) { if (!interruptThrown && (std::uncaught_exceptions() == 0)) {
interruptThrown = true; interruptThrown = true;
throw Interrupted("interrupted by the user"); throw Interrupted("interrupted by the user");
} }
@ -1182,7 +1185,7 @@ template vector<string> tokenizeString(const string& s,
string concatStringsSep(const string& sep, const Strings& ss) { string concatStringsSep(const string& sep, const Strings& ss) {
string s; string s;
for (auto& i : ss) { for (auto& i : ss) {
if (s.size() != 0) { if (!s.empty()) {
s += sep; s += sep;
} }
s += i; s += i;
@ -1193,7 +1196,7 @@ string concatStringsSep(const string& sep, const Strings& ss) {
string concatStringsSep(const string& sep, const StringSet& ss) { string concatStringsSep(const string& sep, const StringSet& ss) {
string s; string s;
for (auto& i : ss) { for (auto& i : ss) {
if (s.size() != 0) { if (!s.empty()) {
s += sep; s += sep;
} }
s += i; s += i;
@ -1233,7 +1236,8 @@ string statusToString(int status) {
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
if (WIFEXITED(status)) { if (WIFEXITED(status)) {
return (format("failed with exit code %1%") % WEXITSTATUS(status)).str(); return (format("failed with exit code %1%") % WEXITSTATUS(status)).str();
} else if (WIFSIGNALED(status)) { }
if (WIFSIGNALED(status)) {
int sig = WTERMSIG(status); int sig = WTERMSIG(status);
#if HAVE_STRSIGNAL #if HAVE_STRSIGNAL
const char* description = strsignal(sig); const char* description = strsignal(sig);
@ -1294,7 +1298,8 @@ void ignoreException() {
std::string filterANSIEscapes(const std::string& s, bool filterAll, std::string filterANSIEscapes(const std::string& s, bool filterAll,
unsigned int width) { unsigned int width) {
std::string t, e; std::string t;
std::string e;
size_t w = 0; size_t w = 0;
auto i = s.begin(); auto i = s.begin();
@ -1333,7 +1338,7 @@ std::string filterANSIEscapes(const std::string& s, bool filterAll,
i++; i++;
t += ' '; t += ' ';
w++; w++;
while (w < (size_t)width && w % 8) { while (w < (size_t)width && ((w % 8) != 0u)) {
t += ' '; t += ' ';
w++; w++;
} }
@ -1357,7 +1362,8 @@ static char base64Chars[] =
string base64Encode(const string& s) { string base64Encode(const string& s) {
string res; string res;
int data = 0, nbits = 0; int data = 0;
int nbits = 0;
for (char c : s) { for (char c : s) {
data = data << 8 | (unsigned char)c; data = data << 8 | (unsigned char)c;
@ -1368,10 +1374,10 @@ string base64Encode(const string& s) {
} }
} }
if (nbits) { if (nbits != 0) {
res.push_back(base64Chars[data << (6 - nbits) & 0x3f]); res.push_back(base64Chars[data << (6 - nbits) & 0x3f]);
} }
while (res.size() % 4) { while ((res.size() % 4) != 0u) {
res.push_back('='); res.push_back('=');
} }
@ -1391,7 +1397,8 @@ string base64Decode(const string& s) {
} }
string res; string res;
unsigned int d = 0, bits = 0; unsigned int d = 0;
unsigned int bits = 0;
for (char c : s) { for (char c : s) {
if (c == '=') { if (c == '=') {
@ -1478,7 +1485,7 @@ static sigset_t savedSignalMask;
void startSignalHandlerThread() { void startSignalHandlerThread() {
updateWindowSize(); updateWindowSize();
if (sigprocmask(SIG_BLOCK, nullptr, &savedSignalMask)) { if (sigprocmask(SIG_BLOCK, nullptr, &savedSignalMask) != 0) {
throw SysError("quering signal mask"); throw SysError("quering signal mask");
} }
@ -1489,7 +1496,7 @@ void startSignalHandlerThread() {
sigaddset(&set, SIGHUP); sigaddset(&set, SIGHUP);
sigaddset(&set, SIGPIPE); sigaddset(&set, SIGPIPE);
sigaddset(&set, SIGWINCH); sigaddset(&set, SIGWINCH);
if (pthread_sigmask(SIG_BLOCK, &set, nullptr)) { if (pthread_sigmask(SIG_BLOCK, &set, nullptr) != 0) {
throw SysError("blocking signals"); throw SysError("blocking signals");
} }
@ -1497,7 +1504,7 @@ void startSignalHandlerThread() {
} }
void restoreSignals() { void restoreSignals() {
if (sigprocmask(SIG_SETMASK, &savedSignalMask, nullptr)) { if (sigprocmask(SIG_SETMASK, &savedSignalMask, nullptr) != 0) {
throw SysError("restoring signals"); throw SysError("restoring signals");
} }
} }

View file

@ -188,10 +188,10 @@ class AutoCloseFD {
AutoCloseFD(); AutoCloseFD();
AutoCloseFD(int fd); AutoCloseFD(int fd);
AutoCloseFD(const AutoCloseFD& fd) = delete; AutoCloseFD(const AutoCloseFD& fd) = delete;
AutoCloseFD(AutoCloseFD&& fd); AutoCloseFD(AutoCloseFD&& that);
~AutoCloseFD(); ~AutoCloseFD();
AutoCloseFD& operator=(const AutoCloseFD& fd) = delete; AutoCloseFD& operator=(const AutoCloseFD& fd) = delete;
AutoCloseFD& operator=(AutoCloseFD&& fd); AutoCloseFD& operator=(AutoCloseFD&& that);
int get() const; int get() const;
explicit operator bool() const; explicit operator bool() const;
int release(); int release();

View file

@ -23,7 +23,7 @@
using namespace nix; using namespace nix;
using namespace std::string_literals; using namespace std::string_literals;
extern char** environ __attribute__((weak)); __attribute__((weak));
/* Recreate the effect of the perl shellwords function, breaking up a /* Recreate the effect of the perl shellwords function, breaking up a
* string into arguments like a shell word, including escapes * string into arguments like a shell word, including escapes
@ -75,7 +75,8 @@ static void _main(int argc, char** argv) {
auto fromArgs = false; auto fromArgs = false;
auto packages = false; auto packages = false;
// Same condition as bash uses for interactive shells // Same condition as bash uses for interactive shells
auto interactive = isatty(STDIN_FILENO) && isatty(STDERR_FILENO); auto interactive =
(isatty(STDIN_FILENO) != 0) && (isatty(STDERR_FILENO) != 0);
Strings attrPaths; Strings attrPaths;
Strings left; Strings left;
RepairFlag repair = NoRepair; RepairFlag repair = NoRepair;
@ -344,8 +345,11 @@ static void _main(int argc, char** argv) {
auto buildPaths = [&](const PathSet& paths) { auto buildPaths = [&](const PathSet& paths) {
/* Note: we do this even when !printMissing to efficiently /* Note: we do this even when !printMissing to efficiently
fetch binary cache data. */ fetch binary cache data. */
unsigned long long downloadSize, narSize; unsigned long long downloadSize;
PathSet willBuild, willSubstitute, unknown; unsigned long long narSize;
PathSet willBuild;
PathSet willSubstitute;
PathSet unknown;
store->queryMissing(paths, willBuild, willSubstitute, unknown, downloadSize, store->queryMissing(paths, willBuild, willSubstitute, unknown, downloadSize,
narSize); narSize);
@ -374,7 +378,7 @@ static void _main(int argc, char** argv) {
<nixpkgs>. */ <nixpkgs>. */
auto shell = getEnv("NIX_BUILD_SHELL", ""); auto shell = getEnv("NIX_BUILD_SHELL", "");
if (shell == "") { if (shell.empty()) {
try { try {
auto expr = state->parseExprFromString( auto expr = state->parseExprFromString(
"(import <nixpkgs> {}).bashInteractive", absPath(".")); "(import <nixpkgs> {}).bashInteractive", absPath("."));
@ -427,7 +431,7 @@ static void _main(int argc, char** argv) {
if (pure) { if (pure) {
decltype(env) newEnv; decltype(env) newEnv;
for (auto& i : env) { for (auto& i : env) {
if (keepVars.count(i.first)) { if (keepVars.count(i.first) != 0u) {
newEnv.emplace(i); newEnv.emplace(i);
} }
} }
@ -447,7 +451,7 @@ static void _main(int argc, char** argv) {
int fileNr = 0; int fileNr = 0;
for (auto& var : drv.env) { for (auto& var : drv.env) {
if (passAsFile.count(var.first)) { if (passAsFile.count(var.first) != 0u) {
keepTmp = true; keepTmp = true;
string fn = ".attr-" + std::to_string(fileNr++); string fn = ".attr-" + std::to_string(fileNr++);
Path p = (Path)tmpDir + "/" + fn; Path p = (Path)tmpDir + "/" + fn;
@ -485,8 +489,9 @@ static void _main(int argc, char** argv) {
"%7%", "%7%",
(Path)tmpDir, (pure ? "" : "p=$PATH; "), (Path)tmpDir, (pure ? "" : "p=$PATH; "),
(pure ? "" : "PATH=$PATH:$p; unset p; "), dirOf(shell), shell, (pure ? "" : "PATH=$PATH:$p; unset p; "), dirOf(shell), shell,
(getenv("TZ") ? (string("export TZ='") + getenv("TZ") + "'; ") (getenv("TZ") != nullptr
: ""), ? (string("export TZ='") + getenv("TZ") + "'; ")
: ""),
envCommand)); envCommand));
Strings envStrs; Strings envStrs;
@ -510,60 +515,58 @@ static void _main(int argc, char** argv) {
throw SysError("executing shell '%s'", shell); throw SysError("executing shell '%s'", shell);
} }
else { PathSet pathsToBuild;
PathSet pathsToBuild;
std::map<Path, Path> drvPrefixes; std::map<Path, Path> drvPrefixes;
std::map<Path, Path> resultSymlinks; std::map<Path, Path> resultSymlinks;
std::vector<Path> outPaths; std::vector<Path> outPaths;
for (auto& drvInfo : drvs) { for (auto& drvInfo : drvs) {
auto drvPath = drvInfo.queryDrvPath(); auto drvPath = drvInfo.queryDrvPath();
auto outPath = drvInfo.queryOutPath(); auto outPath = drvInfo.queryOutPath();
auto outputName = drvInfo.queryOutputName(); auto outputName = drvInfo.queryOutputName();
if (outputName == "") { if (outputName.empty()) {
throw Error("derivation '%s' lacks an 'outputName' attribute", drvPath); throw Error("derivation '%s' lacks an 'outputName' attribute", drvPath);
}
pathsToBuild.insert(drvPath + "!" + outputName);
std::string drvPrefix;
auto i = drvPrefixes.find(drvPath);
if (i != drvPrefixes.end()) {
drvPrefix = i->second;
} else {
drvPrefix = outLink;
if (drvPrefixes.size()) {
drvPrefix += fmt("-%d", drvPrefixes.size() + 1);
}
drvPrefixes[drvPath] = drvPrefix;
}
std::string symlink = drvPrefix;
if (outputName != "out") {
symlink += "-" + outputName;
}
resultSymlinks[symlink] = outPath;
outPaths.push_back(outPath);
} }
buildPaths(pathsToBuild); pathsToBuild.insert(drvPath + "!" + outputName);
if (dryRun) { std::string drvPrefix;
return; auto i = drvPrefixes.find(drvPath);
} if (i != drvPrefixes.end()) {
drvPrefix = i->second;
for (auto& symlink : resultSymlinks) { } else {
if (auto store2 = store.dynamic_pointer_cast<LocalFSStore>()) { drvPrefix = outLink;
store2->addPermRoot(symlink.second, absPath(symlink.first), true); if (!drvPrefixes.empty() != 0u) {
drvPrefix += fmt("-%d", drvPrefixes.size() + 1);
} }
drvPrefixes[drvPath] = drvPrefix;
} }
for (auto& path : outPaths) { std::string symlink = drvPrefix;
std::cout << path << '\n'; if (outputName != "out") {
symlink += "-" + outputName;
} }
resultSymlinks[symlink] = outPath;
outPaths.push_back(outPath);
}
buildPaths(pathsToBuild);
if (dryRun) {
return;
}
for (auto& symlink : resultSymlinks) {
if (auto store2 = store.dynamic_pointer_cast<LocalFSStore>()) {
store2->addPermRoot(symlink.second, absPath(symlink.first), true);
}
}
for (auto& path : outPaths) {
std::cout << path << '\n';
} }
} }

View file

@ -86,7 +86,7 @@ static void update(const StringSet& channelNames) {
for (const auto& channel : channels) { for (const auto& channel : channels) {
auto name = channel.first; auto name = channel.first;
auto url = channel.second; auto url = channel.second;
if (!(channelNames.empty() || channelNames.count(name))) { if (!(channelNames.empty() || (channelNames.count(name) != 0u))) {
continue; continue;
} }
@ -216,7 +216,7 @@ static int _main(int argc, char** argv) {
case cNone: case cNone:
throw UsageError("no command specified"); throw UsageError("no command specified");
case cAdd: case cAdd:
if (args.size() < 1 || args.size() > 2) { if (args.empty() || args.size() > 2) {
throw UsageError("'--add' requires one or two arguments"); throw UsageError("'--add' requires one or two arguments");
} }
{ {

View file

@ -42,7 +42,7 @@ void removeOldGenerations(std::string dir) {
} }
if (link.find("link") != string::npos) { if (link.find("link") != string::npos) {
LOG(INFO) << "removing old generations of profile " << path; LOG(INFO) << "removing old generations of profile " << path;
if (deleteOlderThan != "") { if (!deleteOlderThan.empty()) {
deleteGenerationsOlderThan(path, deleteOlderThan, dryRun); deleteGenerationsOlderThan(path, deleteOlderThan, dryRun);
} else { } else {
deleteOldGenerations(path, dryRun); deleteOldGenerations(path, dryRun);

View file

@ -209,7 +209,7 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
store->assertStorePath(path); store->assertStorePath(path);
bool result = store->isValidPath(path); bool result = store->isValidPath(path);
logger->stopWork(); logger->stopWork();
to << result; to << static_cast<uint64_t>(result);
break; break;
} }
@ -227,7 +227,7 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
logger->startWork(); logger->startWork();
PathSet res = store->querySubstitutablePaths({path}); PathSet res = store->querySubstitutablePaths({path});
logger->stopWork(); logger->stopWork();
to << (res.find(path) != res.end()); to << static_cast<uint64_t>(res.find(path) != res.end());
break; break;
} }
@ -299,8 +299,10 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
} }
case wopAddToStore: { case wopAddToStore: {
bool fixed, recursive; bool fixed;
std::string s, baseName; bool recursive;
std::string s;
std::string baseName;
from >> baseName >> fixed /* obsolete */ >> recursive >> s; from >> baseName >> fixed /* obsolete */ >> recursive >> s;
/* Compatibility hack. */ /* Compatibility hack. */
if (!fixed) { if (!fixed) {
@ -490,9 +492,9 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
} }
case wopSetOptions: { case wopSetOptions: {
settings.keepFailed = readInt(from); settings.keepFailed = readInt(from) != 0u;
settings.keepGoing = readInt(from); settings.keepGoing = readInt(from) != 0u;
settings.tryFallback = readInt(from); settings.tryFallback = readInt(from) != 0u;
readInt(from); // obsolete verbosity readInt(from); // obsolete verbosity
settings.maxBuildJobs.assign(readInt(from)); settings.maxBuildJobs.assign(readInt(from));
settings.maxSilentTime = readInt(from); settings.maxSilentTime = readInt(from);
@ -501,7 +503,7 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
readInt(from); // obsolete logType readInt(from); // obsolete logType
readInt(from); // obsolete printBuildTrace readInt(from); // obsolete printBuildTrace
settings.buildCores = readInt(from); settings.buildCores = readInt(from);
settings.useSubstitutes = readInt(from); settings.useSubstitutes = readInt(from) != 0u;
StringMap overrides; StringMap overrides;
if (GET_PROTOCOL_MINOR(clientVersion) >= 12) { if (GET_PROTOCOL_MINOR(clientVersion) >= 12) {
@ -530,7 +532,7 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
Strings subs; Strings subs;
auto ss = tokenizeString<Strings>(value); auto ss = tokenizeString<Strings>(value);
for (auto& s : ss) { for (auto& s : ss) {
if (trusted.count(s)) { if (trusted.count(s) != 0u) {
subs.push_back(s); subs.push_back(s);
} else { } else {
LOG(WARNING) << "ignoring untrusted substituter '" << s << "'"; LOG(WARNING) << "ignoring untrusted substituter '" << s << "'";
@ -545,7 +547,7 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
; ;
} else if (trusted || name == settings.buildTimeout.name || } else if (trusted || name == settings.buildTimeout.name ||
name == "connect-timeout" || name == "connect-timeout" ||
(name == "builders" && value == "")) { (name == "builders" && value.empty())) {
settings.set(name, value); settings.set(name, value);
} else if (setSubstituters(settings.substituters)) { } else if (setSubstituters(settings.substituters)) {
; ;
@ -622,7 +624,7 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
to << info->deriver << info->narHash.to_string(Base16, false) to << info->deriver << info->narHash.to_string(Base16, false)
<< info->references << info->registrationTime << info->narSize; << info->references << info->registrationTime << info->narSize;
if (GET_PROTOCOL_MINOR(clientVersion) >= 16) { if (GET_PROTOCOL_MINOR(clientVersion) >= 16) {
to << info->ultimate << info->sigs << info->ca; to << static_cast<uint64_t>(info->ultimate) << info->sigs << info->ca;
} }
} else { } else {
assert(GET_PROTOCOL_MINOR(clientVersion) >= 17); assert(GET_PROTOCOL_MINOR(clientVersion) >= 17);
@ -639,7 +641,8 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
break; break;
case wopVerifyStore: { case wopVerifyStore: {
bool checkContents, repair; bool checkContents;
bool repair;
from >> checkContents >> repair; from >> checkContents >> repair;
logger->startWork(); logger->startWork();
if (repair && !trusted) { if (repair && !trusted) {
@ -647,7 +650,7 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
} }
bool errors = store->verifyStore(checkContents, (RepairFlag)repair); bool errors = store->verifyStore(checkContents, (RepairFlag)repair);
logger->stopWork(); logger->stopWork();
to << errors; to << static_cast<uint64_t>(errors);
break; break;
} }
@ -673,7 +676,8 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
} }
case wopAddToStoreNar: { case wopAddToStoreNar: {
bool repair, dontCheckSigs; bool repair;
bool dontCheckSigs;
ValidPathInfo info; ValidPathInfo info;
info.path = readStorePath(*store, from); info.path = readStorePath(*store, from);
from >> info.deriver; from >> info.deriver;
@ -716,8 +720,11 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
case wopQueryMissing: { case wopQueryMissing: {
auto targets = readStorePaths<PathSet>(*store, from); auto targets = readStorePaths<PathSet>(*store, from);
logger->startWork(); logger->startWork();
PathSet willBuild, willSubstitute, unknown; PathSet willBuild;
unsigned long long downloadSize, narSize; PathSet willSubstitute;
PathSet unknown;
unsigned long long downloadSize;
unsigned long long narSize;
store->queryMissing(targets, willBuild, willSubstitute, unknown, store->queryMissing(targets, willBuild, willSubstitute, unknown,
downloadSize, narSize); downloadSize, narSize);
logger->stopWork(); logger->stopWork();
@ -757,7 +764,7 @@ static void processConnection(bool trusted, const std::string& userName,
DLOG(INFO) << opCount << " operations"; DLOG(INFO) << opCount << " operations";
}); });
if (GET_PROTOCOL_MINOR(clientVersion) >= 14 && readInt(from)) { if (GET_PROTOCOL_MINOR(clientVersion) >= 14 && (readInt(from) != 0u)) {
setAffinityTo(readInt(from)); setAffinityTo(readInt(from));
} }
@ -842,11 +849,12 @@ static void sigChldHandler(int sigNo) {
} }
static void setSigChldAction(bool autoReap) { static void setSigChldAction(bool autoReap) {
struct sigaction act, oact; struct sigaction act;
struct sigaction oact;
act.sa_handler = autoReap ? sigChldHandler : SIG_DFL; act.sa_handler = autoReap ? sigChldHandler : SIG_DFL;
sigfillset(&act.sa_mask); sigfillset(&act.sa_mask);
act.sa_flags = 0; act.sa_flags = 0;
if (sigaction(SIGCHLD, &act, &oact)) { if (sigaction(SIGCHLD, &act, &oact) != 0) {
throw SysError("setting SIGCHLD handler"); throw SysError("setting SIGCHLD handler");
} }
} }
@ -866,10 +874,10 @@ bool matchUser(const string& user, const string& group, const Strings& users) {
return true; return true;
} }
struct group* gr = getgrnam(i.c_str() + 1); struct group* gr = getgrnam(i.c_str() + 1);
if (!gr) { if (gr == nullptr) {
continue; continue;
} }
for (char** mem = gr->gr_mem; *mem; mem++) { for (char** mem = gr->gr_mem; *mem != nullptr; mem++) {
if (user == string(*mem)) { if (user == string(*mem)) {
return true; return true;
} }
@ -933,7 +941,7 @@ static void daemonLoop(char** argv) {
AutoCloseFD fdSocket; AutoCloseFD fdSocket;
/* Handle socket-based activation by systemd. */ /* Handle socket-based activation by systemd. */
if (getEnv("LISTEN_FDS") != "") { if (!getEnv("LISTEN_FDS").empty()) {
if (getEnv("LISTEN_PID") != std::to_string(getpid()) || if (getEnv("LISTEN_PID") != std::to_string(getpid()) ||
getEnv("LISTEN_FDS") != "1") { getEnv("LISTEN_FDS") != "1") {
throw Error("unexpected systemd environment variables"); throw Error("unexpected systemd environment variables");
@ -1014,10 +1022,10 @@ static void daemonLoop(char** argv) {
PeerInfo peer = getPeerInfo(remote.get()); PeerInfo peer = getPeerInfo(remote.get());
struct passwd* pw = peer.uidKnown ? getpwuid(peer.uid) : nullptr; struct passwd* pw = peer.uidKnown ? getpwuid(peer.uid) : nullptr;
string user = pw ? pw->pw_name : std::to_string(peer.uid); string user = pw != nullptr ? pw->pw_name : std::to_string(peer.uid);
struct group* gr = peer.gidKnown ? getgrgid(peer.gid) : nullptr; struct group* gr = peer.gidKnown ? getgrgid(peer.gid) : nullptr;
string group = gr ? gr->gr_name : std::to_string(peer.gid); string group = gr != nullptr ? gr->gr_name : std::to_string(peer.gid);
Strings trustedUsers = settings.trustedUsers; Strings trustedUsers = settings.trustedUsers;
Strings allowedUsers = settings.allowedUsers; Strings allowedUsers = settings.allowedUsers;
@ -1057,7 +1065,7 @@ static void daemonLoop(char** argv) {
setSigChldAction(false); setSigChldAction(false);
/* For debugging, stuff the pid into argv[1]. */ /* For debugging, stuff the pid into argv[1]. */
if (peer.pidKnown && argv[1]) { if (peer.pidKnown && (argv[1] != nullptr)) {
string processName = std::to_string(peer.pid); string processName = std::to_string(peer.pid);
strncpy(argv[1], processName.c_str(), strlen(argv[1])); strncpy(argv[1], processName.c_str(), strlen(argv[1]));
} }
@ -1143,7 +1151,8 @@ static int _main(int argc, char** argv) {
SPLICE_F_MOVE); SPLICE_F_MOVE);
if (res == -1) { if (res == -1) {
throw SysError("splicing data from daemon socket to stdout"); throw SysError("splicing data from daemon socket to stdout");
} else if (res == 0) { }
if (res == 0) {
throw EndOfFile("unexpected EOF from daemon socket"); throw EndOfFile("unexpected EOF from daemon socket");
} }
} }
@ -1152,7 +1161,8 @@ static int _main(int argc, char** argv) {
SPLICE_F_MOVE); SPLICE_F_MOVE);
if (res == -1) { if (res == -1) {
throw SysError("splicing data from stdin to daemon socket"); throw SysError("splicing data from stdin to daemon socket");
} else if (res == 0) { }
if (res == 0) {
return 0; return 0;
} }
} }

View file

@ -319,7 +319,7 @@ static void queryInstSources(EvalState& state, InstallSourceInfo& instSource,
const Strings& args, DrvInfos& elems, const Strings& args, DrvInfos& elems,
bool newestOnly) { bool newestOnly) {
InstallSourceType type = instSource.type; InstallSourceType type = instSource.type;
if (type == srcUnknown && args.size() > 0 && isPath(args.front())) { if (type == srcUnknown && !args.empty() && isPath(args.front())) {
type = srcStorePaths; type = srcStorePaths;
} }
@ -352,7 +352,8 @@ static void queryInstSources(EvalState& state, InstallSourceInfo& instSource,
for (auto& i : args) { for (auto& i : args) {
Expr* eFun = state.parseExprFromString(i, absPath(".")); Expr* eFun = state.parseExprFromString(i, absPath("."));
Value vFun, vTmp; Value vFun;
Value vTmp;
state.eval(eFun, vFun); state.eval(eFun, vFun);
mkApp(vTmp, vFun, vArg); mkApp(vTmp, vFun, vArg);
getDerivations(state, vTmp, "", *instSource.autoArgs, elems, true); getDerivations(state, vTmp, "", *instSource.autoArgs, elems, true);
@ -420,7 +421,7 @@ static void printMissing(EvalState& state, DrvInfos& elems) {
PathSet targets; PathSet targets;
for (auto& i : elems) { for (auto& i : elems) {
Path drvPath = i.queryDrvPath(); Path drvPath = i.queryDrvPath();
if (drvPath != "") { if (!drvPath.empty()) {
targets.insert(drvPath); targets.insert(drvPath);
} else { } else {
targets.insert(i.queryOutPath()); targets.insert(i.queryOutPath());
@ -437,7 +438,8 @@ static void installDerivations(Globals& globals, const Strings& args,
DLOG(INFO) << "installing derivations"; DLOG(INFO) << "installing derivations";
/* Get the set of user environment elements to be installed. */ /* Get the set of user environment elements to be installed. */
DrvInfos newElems, newElemsTmp; DrvInfos newElems;
DrvInfos newElemsTmp;
queryInstSources(*globals.state, globals.instSource, args, newElemsTmp, true); queryInstSources(*globals.state, globals.instSource, args, newElemsTmp, true);
/* If --prebuilt-only is given, filter out source-only packages. */ /* If --prebuilt-only is given, filter out source-only packages. */
@ -453,7 +455,7 @@ static void installDerivations(Globals& globals, const Strings& args,
one-click installs, namely those where the name used in the one-click installs, namely those where the name used in the
path is not the one we want (e.g., `java-front' versus path is not the one we want (e.g., `java-front' versus
`java-front-0.9pre15899'). */ `java-front-0.9pre15899'). */
if (globals.forceName != "") { if (!globals.forceName.empty()) {
i.setName(globals.forceName); i.setName(globals.forceName);
} }
newNames.insert(DrvName(i.queryName()).name); newNames.insert(DrvName(i.queryName()).name);
@ -644,7 +646,7 @@ static void setMetaFlag(EvalState& state, DrvInfo& drv, const string& name,
} }
static void opSetFlag(Globals& globals, Strings opFlags, Strings opArgs) { static void opSetFlag(Globals& globals, Strings opFlags, Strings opArgs) {
if (opFlags.size() > 0) { if (!opFlags.empty()) {
throw UsageError(format("unknown flag '%1%'") % opFlags.front()); throw UsageError(format("unknown flag '%1%'") % opFlags.front());
} }
if (opArgs.size() < 2) { if (opArgs.size() < 2) {
@ -708,18 +710,18 @@ static void opSet(Globals& globals, Strings opFlags, Strings opArgs) {
DrvInfo& drv(elems.front()); DrvInfo& drv(elems.front());
if (globals.forceName != "") { if (!globals.forceName.empty()) {
drv.setName(globals.forceName); drv.setName(globals.forceName);
} }
if (drv.queryDrvPath() != "") { if (!drv.queryDrvPath().empty()) {
PathSet paths = {drv.queryDrvPath()}; PathSet paths = {drv.queryDrvPath()};
printMissing(globals.state->store, paths); printMissing(globals.state->store, paths);
if (globals.dryRun) { if (globals.dryRun) {
return; return;
} }
globals.state->store->buildPaths( globals.state->store->buildPaths(
paths, globals.state->repair ? bmRepair : bmNormal); paths, globals.state->repair != 0u ? bmRepair : bmNormal);
} else { } else {
printMissing(globals.state->store, {drv.queryOutPath()}); printMissing(globals.state->store, {drv.queryOutPath()});
if (globals.dryRun) { if (globals.dryRun) {
@ -774,7 +776,7 @@ static void uninstallDerivations(Globals& globals, Strings& selectors,
} }
static void opUninstall(Globals& globals, Strings opFlags, Strings opArgs) { static void opUninstall(Globals& globals, Strings opFlags, Strings opArgs) {
if (opFlags.size() > 0) { if (!opFlags.empty()) {
throw UsageError(format("unknown flag '%1%'") % opFlags.front()); throw UsageError(format("unknown flag '%1%'") % opFlags.front());
} }
uninstallDerivations(globals, opArgs, globals.profile); uninstallDerivations(globals, opArgs, globals.profile);
@ -792,7 +794,7 @@ static bool cmpElemByName(const DrvInfo& a, const DrvInfo& b) {
using Table = list<Strings>; using Table = list<Strings>;
void printTable(Table& table) { void printTable(Table& table) {
auto nrColumns = table.size() > 0 ? table.front().size() : 0; auto nrColumns = !table.empty() ? table.front().size() : 0;
vector<size_t> widths; vector<size_t> widths;
widths.resize(nrColumns); widths.resize(nrColumns);
@ -852,7 +854,7 @@ static VersionDiff compareVersionAgainstSet(const DrvInfo& elem,
version = name2.version; version = name2.version;
} else if (diff != cvGreater && diff != cvEqual && d > 0) { } else if (diff != cvGreater && diff != cvEqual && d > 0) {
diff = cvLess; diff = cvLess;
if (version == "" || compareVersions(version, name2.version) < 0) { if (version.empty() || compareVersions(version, name2.version) < 0) {
version = name2.version; version = name2.version;
} }
} }
@ -878,7 +880,7 @@ static void queryJSON(Globals& globals, vector<DrvInfo>& elems) {
for (auto& j : metaNames) { for (auto& j : metaNames) {
auto placeholder = metaObj.placeholder(j); auto placeholder = metaObj.placeholder(j);
Value* v = i.queryMeta(j); Value* v = i.queryMeta(j);
if (!v) { if (v == nullptr) {
LOG(ERROR) << "derivation '" << i.queryName() LOG(ERROR) << "derivation '" << i.queryName()
<< "' has invalid meta attribute '" << j << "'"; << "' has invalid meta attribute '" << j << "'";
placeholder.write(nullptr); placeholder.write(nullptr);
@ -946,7 +948,8 @@ static void opQuery(Globals& globals, Strings opFlags, Strings opArgs) {
} }
/* Obtain derivation information from the specified source. */ /* Obtain derivation information from the specified source. */
DrvInfos availElems, installedElems; DrvInfos availElems;
DrvInfos installedElems;
if (source == sInstalled || compareVersions || printStatus) { if (source == sInstalled || compareVersions || printStatus) {
installedElems = queryInstalled(*globals.state, globals.profile); installedElems = queryInstalled(*globals.state, globals.profile);
@ -983,7 +986,8 @@ static void opQuery(Globals& globals, Strings opFlags, Strings opArgs) {
} }
/* Query which paths have substitutes. */ /* Query which paths have substitutes. */
PathSet validPaths, substitutablePaths; PathSet validPaths;
PathSet substitutablePaths;
if (printStatus || globals.prebuiltOnly) { if (printStatus || globals.prebuiltOnly) {
PathSet paths; PathSet paths;
for (auto& i : elems) { for (auto& i : elems) {
@ -1005,7 +1009,7 @@ static void opQuery(Globals& globals, Strings opFlags, Strings opArgs) {
return; return;
} }
bool tty = isatty(STDOUT_FILENO); bool tty = isatty(STDOUT_FILENO) != 0;
RunPager pager; RunPager pager;
Table table; Table table;
@ -1107,7 +1111,7 @@ static void opQuery(Globals& globals, Strings opFlags, Strings opArgs) {
} }
if (xmlOutput) { if (xmlOutput) {
if (i.querySystem() != "") { if (!i.querySystem().empty()) {
attrs["system"] = i.querySystem(); attrs["system"] = i.querySystem();
} }
} else if (printSystem) { } else if (printSystem) {
@ -1117,11 +1121,11 @@ static void opQuery(Globals& globals, Strings opFlags, Strings opArgs) {
if (printDrvPath) { if (printDrvPath) {
string drvPath = i.queryDrvPath(); string drvPath = i.queryDrvPath();
if (xmlOutput) { if (xmlOutput) {
if (drvPath != "") { if (!drvPath.empty()) {
attrs["drvPath"] = drvPath; attrs["drvPath"] = drvPath;
} }
} else { } else {
columns.push_back(drvPath == "" ? "-" : drvPath); columns.push_back(drvPath.empty() ? "-" : drvPath);
} }
} }
@ -1144,7 +1148,7 @@ static void opQuery(Globals& globals, Strings opFlags, Strings opArgs) {
if (printDescription) { if (printDescription) {
string descr = i.queryMetaString("description"); string descr = i.queryMetaString("description");
if (xmlOutput) { if (xmlOutput) {
if (descr != "") { if (!descr.empty()) {
attrs["description"] = descr; attrs["description"] = descr;
} }
} else { } else {
@ -1170,7 +1174,7 @@ static void opQuery(Globals& globals, Strings opFlags, Strings opArgs) {
XMLAttrs attrs2; XMLAttrs attrs2;
attrs2["name"] = j; attrs2["name"] = j;
Value* v = i.queryMeta(j); Value* v = i.queryMeta(j);
if (!v) { if (v == nullptr) {
LOG(ERROR) << "derivation '" << i.queryName() LOG(ERROR) << "derivation '" << i.queryName()
<< "' has invalid meta attribute '" << j << "'"; << "' has invalid meta attribute '" << j << "'";
} else { } else {
@ -1244,7 +1248,7 @@ static void opQuery(Globals& globals, Strings opFlags, Strings opArgs) {
} }
static void opSwitchProfile(Globals& globals, Strings opFlags, Strings opArgs) { static void opSwitchProfile(Globals& globals, Strings opFlags, Strings opArgs) {
if (opFlags.size() > 0) { if (!opFlags.empty()) {
throw UsageError(format("unknown flag '%1%'") % opFlags.front()); throw UsageError(format("unknown flag '%1%'") % opFlags.front());
} }
if (opArgs.size() != 1) { if (opArgs.size() != 1) {
@ -1278,9 +1282,8 @@ static void switchGeneration(Globals& globals, int dstGen) {
if (dstGen == prevGen) { if (dstGen == prevGen) {
throw Error(format("no generation older than the current (%1%) exists") % throw Error(format("no generation older than the current (%1%) exists") %
curGen); curGen);
} else {
throw Error(format("generation %1% does not exist") % dstGen);
} }
throw Error(format("generation %1% does not exist") % dstGen);
} }
LOG(INFO) << "switching from generation " << curGen << " to " << dst.number; LOG(INFO) << "switching from generation " << curGen << " to " << dst.number;
@ -1294,7 +1297,7 @@ static void switchGeneration(Globals& globals, int dstGen) {
static void opSwitchGeneration(Globals& globals, Strings opFlags, static void opSwitchGeneration(Globals& globals, Strings opFlags,
Strings opArgs) { Strings opArgs) {
if (opFlags.size() > 0) { if (!opFlags.empty()) {
throw UsageError(format("unknown flag '%1%'") % opFlags.front()); throw UsageError(format("unknown flag '%1%'") % opFlags.front());
} }
if (opArgs.size() != 1) { if (opArgs.size() != 1) {
@ -1310,10 +1313,10 @@ static void opSwitchGeneration(Globals& globals, Strings opFlags,
} }
static void opRollback(Globals& globals, Strings opFlags, Strings opArgs) { static void opRollback(Globals& globals, Strings opFlags, Strings opArgs) {
if (opFlags.size() > 0) { if (!opFlags.empty()) {
throw UsageError(format("unknown flag '%1%'") % opFlags.front()); throw UsageError(format("unknown flag '%1%'") % opFlags.front());
} }
if (opArgs.size() != 0) { if (!opArgs.empty()) {
throw UsageError(format("no arguments expected")); throw UsageError(format("no arguments expected"));
} }
@ -1322,10 +1325,10 @@ static void opRollback(Globals& globals, Strings opFlags, Strings opArgs) {
static void opListGenerations(Globals& globals, Strings opFlags, static void opListGenerations(Globals& globals, Strings opFlags,
Strings opArgs) { Strings opArgs) {
if (opFlags.size() > 0) { if (!opFlags.empty()) {
throw UsageError(format("unknown flag '%1%'") % opFlags.front()); throw UsageError(format("unknown flag '%1%'") % opFlags.front());
} }
if (opArgs.size() != 0) { if (!opArgs.empty()) {
throw UsageError(format("no arguments expected")); throw UsageError(format("no arguments expected"));
} }
@ -1339,7 +1342,7 @@ static void opListGenerations(Globals& globals, Strings opFlags,
for (auto& i : gens) { for (auto& i : gens) {
tm t; tm t;
if (!localtime_r(&i.creationTime, &t)) { if (localtime_r(&i.creationTime, &t) == nullptr) {
throw Error("cannot convert time"); throw Error("cannot convert time");
} }
cout << format("%|4| %|4|-%|02|-%|02| %|02|:%|02|:%|02| %||\n") % cout << format("%|4| %|4|-%|02|-%|02| %|02|:%|02|:%|02| %||\n") %
@ -1351,7 +1354,7 @@ static void opListGenerations(Globals& globals, Strings opFlags,
static void opDeleteGenerations(Globals& globals, Strings opFlags, static void opDeleteGenerations(Globals& globals, Strings opFlags,
Strings opArgs) { Strings opArgs) {
if (opFlags.size() > 0) { if (!opFlags.empty()) {
throw UsageError(format("unknown flag '%1%'") % opFlags.front()); throw UsageError(format("unknown flag '%1%'") % opFlags.front());
} }
@ -1390,7 +1393,8 @@ static void opVersion(Globals& globals, Strings opFlags, Strings opArgs) {
static int _main(int argc, char** argv) { static int _main(int argc, char** argv) {
{ {
Strings opFlags, opArgs; Strings opFlags;
Strings opArgs;
Operation op = nullptr; Operation op = nullptr;
RepairFlag repair = NoRepair; RepairFlag repair = NoRepair;
string file; string file;
@ -1482,7 +1486,7 @@ static int _main(int argc, char** argv) {
opArgs.push_back(*arg); opArgs.push_back(*arg);
} }
if (oldOp && oldOp != op) { if ((oldOp != nullptr) && oldOp != op) {
throw UsageError("only one operation may be specified"); throw UsageError("only one operation may be specified");
} }
@ -1493,7 +1497,7 @@ static int _main(int argc, char** argv) {
initPlugins(); initPlugins();
if (!op) { if (op == nullptr) {
throw UsageError("no operation specified"); throw UsageError("no operation specified");
} }
@ -1503,17 +1507,17 @@ static int _main(int argc, char** argv) {
std::shared_ptr<EvalState>(new EvalState(myArgs.searchPath, store)); std::shared_ptr<EvalState>(new EvalState(myArgs.searchPath, store));
globals.state->repair = repair; globals.state->repair = repair;
if (file != "") { if (!file.empty()) {
globals.instSource.nixExprPath = lookupFileArg(*globals.state, file); globals.instSource.nixExprPath = lookupFileArg(*globals.state, file);
} }
globals.instSource.autoArgs = myArgs.getAutoArgs(*globals.state); globals.instSource.autoArgs = myArgs.getAutoArgs(*globals.state);
if (globals.profile == "") { if (globals.profile.empty()) {
globals.profile = getEnv("NIX_PROFILE", ""); globals.profile = getEnv("NIX_PROFILE", "");
} }
if (globals.profile == "") { if (globals.profile.empty()) {
Path profileLink = getHome() + "/.nix-profile"; Path profileLink = getHome() + "/.nix-profile";
try { try {
if (!pathExists(profileLink)) { if (!pathExists(profileLink)) {

View file

@ -31,13 +31,14 @@ bool createUserEnv(EvalState& state, DrvInfos& elems, const Path& profile,
exist already. */ exist already. */
PathSet drvsToBuild; PathSet drvsToBuild;
for (auto& i : elems) { for (auto& i : elems) {
if (i.queryDrvPath() != "") { if (!i.queryDrvPath().empty()) {
drvsToBuild.insert(i.queryDrvPath()); drvsToBuild.insert(i.queryDrvPath());
} }
} }
DLOG(INFO) << "building user environment dependencies"; DLOG(INFO) << "building user environment dependencies";
state.store->buildPaths(drvsToBuild, state.repair ? bmRepair : bmNormal); state.store->buildPaths(drvsToBuild,
state.repair != 0u ? bmRepair : bmNormal);
/* Construct the whole top level derivation. */ /* Construct the whole top level derivation. */
PathSet references; PathSet references;
@ -61,7 +62,7 @@ bool createUserEnv(EvalState& state, DrvInfos& elems, const Path& profile,
mkString(*state.allocAttr(v, state.sSystem), system); mkString(*state.allocAttr(v, state.sSystem), system);
} }
mkString(*state.allocAttr(v, state.sOutPath), i.queryOutPath()); mkString(*state.allocAttr(v, state.sOutPath), i.queryOutPath());
if (drvPath != "") { if (!drvPath.empty()) {
mkString(*state.allocAttr(v, state.sDrvPath), i.queryDrvPath()); mkString(*state.allocAttr(v, state.sDrvPath), i.queryDrvPath());
} }
@ -90,7 +91,7 @@ bool createUserEnv(EvalState& state, DrvInfos& elems, const Path& profile,
StringSet metaNames = i.queryMetaNames(); StringSet metaNames = i.queryMetaNames();
for (auto& j : metaNames) { for (auto& j : metaNames) {
Value* v = i.queryMeta(j); Value* v = i.queryMeta(j);
if (!v) { if (v == nullptr) {
continue; continue;
} }
vMeta.attrs->push_back(Attr(state.symbols.create(j), v)); vMeta.attrs->push_back(Attr(state.symbols.create(j), v));
@ -98,7 +99,7 @@ bool createUserEnv(EvalState& state, DrvInfos& elems, const Path& profile,
vMeta.attrs->sort(); vMeta.attrs->sort();
v.attrs->sort(); v.attrs->sort();
if (drvPath != "") { if (!drvPath.empty()) {
references.insert(drvPath); references.insert(drvPath);
} }
} }
@ -115,7 +116,8 @@ bool createUserEnv(EvalState& state, DrvInfos& elems, const Path& profile,
/* Construct a Nix expression that calls the user environment /* Construct a Nix expression that calls the user environment
builder with the manifest as argument. */ builder with the manifest as argument. */
Value args, topLevel; Value args;
Value topLevel;
state.mkAttrs(args, 3); state.mkAttrs(args, 3);
mkString(*state.allocAttr(args, state.symbols.create("manifest")), mkString(*state.allocAttr(args, state.symbols.create("manifest")),
manifestFile, {manifestFile}); manifestFile, {manifestFile});
@ -128,15 +130,18 @@ bool createUserEnv(EvalState& state, DrvInfos& elems, const Path& profile,
state.forceValue(topLevel); state.forceValue(topLevel);
PathSet context; PathSet context;
Attr& aDrvPath(*topLevel.attrs->find(state.sDrvPath)); Attr& aDrvPath(*topLevel.attrs->find(state.sDrvPath));
Path topLevelDrv = state.coerceToPath(aDrvPath.pos ? *(aDrvPath.pos) : noPos, Path topLevelDrv =
*(aDrvPath.value), context); state.coerceToPath(aDrvPath.pos != nullptr ? *(aDrvPath.pos) : noPos,
*(aDrvPath.value), context);
Attr& aOutPath(*topLevel.attrs->find(state.sOutPath)); Attr& aOutPath(*topLevel.attrs->find(state.sOutPath));
Path topLevelOut = state.coerceToPath(aOutPath.pos ? *(aOutPath.pos) : noPos, Path topLevelOut =
*(aOutPath.value), context); state.coerceToPath(aOutPath.pos != nullptr ? *(aOutPath.pos) : noPos,
*(aOutPath.value), context);
/* Realise the resulting store expression. */ /* Realise the resulting store expression. */
DLOG(INFO) << "building user environment"; DLOG(INFO) << "building user environment";
state.store->buildPaths({topLevelDrv}, state.repair ? bmRepair : bmNormal); state.store->buildPaths({topLevelDrv},
state.repair != 0u ? bmRepair : bmNormal);
/* Switch the current user environment to the output path. */ /* Switch the current user environment to the output path. */
auto store2 = state.store.dynamic_pointer_cast<LocalFSStore>(); auto store2 = state.store.dynamic_pointer_cast<LocalFSStore>();

View file

@ -63,13 +63,13 @@ void processExpr(EvalState& state, const Strings& attrPaths, bool parseOnly,
/* What output do we want? */ /* What output do we want? */
string outputName = i.queryOutputName(); string outputName = i.queryOutputName();
if (outputName == "") { if (outputName.empty()) {
throw Error( throw Error(
format("derivation '%1%' lacks an 'outputName' attribute ") % format("derivation '%1%' lacks an 'outputName' attribute ") %
drvPath); drvPath);
} }
if (gcRoot == "") { if (gcRoot.empty()) {
printGCWarning(); printGCWarning();
} else { } else {
Path rootName = indirectRoot ? absPath(gcRoot) : gcRoot; Path rootName = indirectRoot ? absPath(gcRoot) : gcRoot;
@ -173,7 +173,7 @@ static int _main(int argc, char** argv) {
if (findFile) { if (findFile) {
for (auto& i : files) { for (auto& i : files) {
Path p = state->findFile(i); Path p = state->findFile(i);
if (p == "") { if (p.empty()) {
throw Error(format("unable to find '%1%'") % i); throw Error(format("unable to find '%1%'") % i);
} }
std::cout << p << std::endl; std::cout << p << std::endl;

View file

@ -57,7 +57,7 @@ static int _main(int argc, char** argv) {
{ {
HashType ht = htSHA256; HashType ht = htSHA256;
std::vector<string> args; std::vector<string> args;
bool printPath = getEnv("PRINT_PATH") != ""; bool printPath = !getEnv("PRINT_PATH").empty();
bool fromExpr = false; bool fromExpr = false;
string attrPath; string attrPath;
bool unpack = false; bool unpack = false;
@ -163,7 +163,8 @@ static int _main(int argc, char** argv) {
/* If an expected hash is given, the file may already exist in /* If an expected hash is given, the file may already exist in
the store. */ the store. */
Hash hash, expectedHash(ht); Hash hash;
Hash expectedHash(ht);
Path storePath; Path storePath;
if (args.size() == 2) { if (args.size() == 2) {
expectedHash = Hash(args[1], ht); expectedHash = Hash(args[1], ht);

View file

@ -58,7 +58,7 @@ void printGraphML(ref<Store> store, const PathSet& roots) {
workList.erase(path); workList.erase(path);
ret = doneSet.insert(path); ret = doneSet.insert(path);
if (ret.second == false) { if (!ret.second) {
continue; continue;
} }

View file

@ -49,7 +49,7 @@ static Path useDeriver(Path path) {
return path; return path;
} }
Path drvPath = store->queryPathInfo(path)->deriver; Path drvPath = store->queryPathInfo(path)->deriver;
if (drvPath == "") { if (drvPath.empty()) {
throw Error(format("deriver of path '%1%' is not known") % path); throw Error(format("deriver of path '%1%' is not known") % path);
} }
return drvPath; return drvPath;
@ -85,7 +85,7 @@ static PathSet realisePath(Path path, bool build = true) {
} }
Path outPath = i->second.path; Path outPath = i->second.path;
if (store2) { if (store2) {
if (gcRoot == "") { if (gcRoot.empty()) {
printGCWarning(); printGCWarning();
} else { } else {
Path rootName = gcRoot; Path rootName = gcRoot;
@ -103,27 +103,25 @@ static PathSet realisePath(Path path, bool build = true) {
return outputs; return outputs;
} }
else { if (build) {
if (build) { store->ensurePath(path);
store->ensurePath(path); } else if (!store->isValidPath(path)) {
} else if (!store->isValidPath(path)) { throw Error(format("path '%1%' does not exist and cannot be created") %
throw Error(format("path '%1%' does not exist and cannot be created") % path);
path);
}
if (store2) {
if (gcRoot == "") {
printGCWarning();
} else {
Path rootName = gcRoot;
rootNr++;
if (rootNr > 1) {
rootName += "-" + std::to_string(rootNr);
}
path = store2->addPermRoot(path, rootName, indirectRoot);
}
}
return {path};
} }
if (store2) {
if (gcRoot.empty()) {
printGCWarning();
} else {
Path rootName = gcRoot;
rootNr++;
if (rootNr > 1) {
rootName += "-" + std::to_string(rootNr);
}
path = store2->addPermRoot(path, rootName, indirectRoot);
}
}
return {path};
} }
/* Realise the given paths. */ /* Realise the given paths. */
@ -153,8 +151,11 @@ static void opRealise(Strings opFlags, Strings opArgs) {
store->followLinksToStorePath(p.first), p.second)); store->followLinksToStorePath(p.first), p.second));
} }
unsigned long long downloadSize, narSize; unsigned long long downloadSize;
PathSet willBuild, willSubstitute, unknown; unsigned long long narSize;
PathSet willBuild;
PathSet willSubstitute;
PathSet unknown;
store->queryMissing(PathSet(paths.begin(), paths.end()), willBuild, store->queryMissing(PathSet(paths.begin(), paths.end()), willBuild,
willSubstitute, unknown, downloadSize, narSize); willSubstitute, unknown, downloadSize, narSize);
@ -267,9 +268,8 @@ static PathSet maybeUseOutputs(const Path& storePath, bool useOutput,
outputs.insert(i.second.path); outputs.insert(i.second.path);
} }
return outputs; return outputs;
} else {
return {storePath};
} }
return {storePath};
} }
/* Some code to print a tree representation of a derivation dependency /* Some code to print a tree representation of a derivation dependency
@ -348,7 +348,7 @@ static void opQuery(Strings opFlags, Strings opArgs) {
} else if (i == "--deriver" || i == "-d") { } else if (i == "--deriver" || i == "-d") {
query = qDeriver; query = qDeriver;
} else if (i == "--binding" || i == "-b") { } else if (i == "--binding" || i == "-b") {
if (opArgs.size() == 0) { if (opArgs.empty()) {
throw UsageError("expected binding name"); throw UsageError("expected binding name");
} }
bindingName = opArgs.front(); bindingName = opArgs.front();
@ -437,7 +437,8 @@ static void opQuery(Strings opFlags, Strings opArgs) {
for (auto& i : opArgs) { for (auto& i : opArgs) {
Path deriver = Path deriver =
store->queryPathInfo(store->followLinksToStorePath(i))->deriver; store->queryPathInfo(store->followLinksToStorePath(i))->deriver;
cout << format("%1%\n") % (deriver == "" ? "unknown-deriver" : deriver); cout << format("%1%\n") %
(deriver.empty() ? "unknown-deriver" : deriver);
} }
break; break;
@ -608,7 +609,7 @@ static void registerValidity(bool reregister, bool hashGiven,
while (true) { while (true) {
ValidPathInfo info = decodeValidPathInfo(cin, hashGiven); ValidPathInfo info = decodeValidPathInfo(cin, hashGiven);
if (info.path == "") { if (info.path.empty()) {
break; break;
} }
if (!store->isValidPath(info.path) || reregister) { if (!store->isValidPath(info.path) || reregister) {
@ -947,7 +948,7 @@ static void opServe(Strings opFlags, Strings opArgs) {
} }
if (GET_PROTOCOL_MINOR(clientVersion) >= 3) { if (GET_PROTOCOL_MINOR(clientVersion) >= 3) {
settings.buildRepeat = readInt(in); settings.buildRepeat = readInt(in);
settings.enforceDeterminism = readInt(in); settings.enforceDeterminism = readInt(in) != 0u;
settings.runDiffHook = true; settings.runDiffHook = true;
} }
settings.printRepeatedBuilds = false; settings.printRepeatedBuilds = false;
@ -963,8 +964,8 @@ static void opServe(Strings opFlags, Strings opArgs) {
switch (cmd) { switch (cmd) {
case cmdQueryValidPaths: { case cmdQueryValidPaths: {
bool lock = readInt(in); bool lock = readInt(in) != 0u;
bool substitute = readInt(in); bool substitute = readInt(in) != 0u;
auto paths = readStorePaths<PathSet>(*store, in); auto paths = readStorePaths<PathSet>(*store, in);
if (lock && writeAllowed) { if (lock && writeAllowed) {
for (auto& path : paths) { for (auto& path : paths) {
@ -983,8 +984,11 @@ static void opServe(Strings opFlags, Strings opArgs) {
paths2.insert(path); paths2.insert(path);
} }
} }
unsigned long long downloadSize, narSize; unsigned long long downloadSize;
PathSet willBuild, willSubstitute, unknown; unsigned long long narSize;
PathSet willBuild;
PathSet willSubstitute;
PathSet unknown;
store->queryMissing(PathSet(paths2.begin(), paths2.end()), willBuild, store->queryMissing(PathSet(paths2.begin(), paths2.end()), willBuild,
willSubstitute, unknown, downloadSize, narSize); willSubstitute, unknown, downloadSize, narSize);
/* FIXME: should use ensurePath(), but it only /* FIXME: should use ensurePath(), but it only
@ -1080,7 +1084,8 @@ static void opServe(Strings opFlags, Strings opArgs) {
out << status.status << status.errorMsg; out << status.status << status.errorMsg;
if (GET_PROTOCOL_MINOR(clientVersion) >= 3) { if (GET_PROTOCOL_MINOR(clientVersion) >= 3) {
out << status.timesBuilt << status.isNonDeterministic out << status.timesBuilt
<< static_cast<uint64_t>(status.isNonDeterministic)
<< status.startTime << status.stopTime; << status.startTime << status.stopTime;
} }
@ -1088,7 +1093,7 @@ static void opServe(Strings opFlags, Strings opArgs) {
} }
case cmdQueryClosure: { case cmdQueryClosure: {
bool includeOutputs = readInt(in); bool includeOutputs = readInt(in) != 0u;
PathSet closure; PathSet closure;
store->computeFSClosure(readStorePaths<PathSet>(*store, in), closure, store->computeFSClosure(readStorePaths<PathSet>(*store, in), closure,
false, includeOutputs); false, includeOutputs);
@ -1184,7 +1189,8 @@ static void opVersion(Strings opFlags, Strings opArgs) {
list. */ list. */
static int _main(int argc, char** argv) { static int _main(int argc, char** argv) {
{ {
Strings opFlags, opArgs; Strings opFlags;
Strings opArgs;
Operation op = nullptr; Operation op = nullptr;
parseCmdLine(argc, argv, parseCmdLine(argc, argv,
@ -1260,7 +1266,7 @@ static int _main(int argc, char** argv) {
opArgs.push_back(*arg); opArgs.push_back(*arg);
} }
if (oldOp && oldOp != op) { if ((oldOp != nullptr) && oldOp != op) {
throw UsageError("only one operation may be specified"); throw UsageError("only one operation may be specified");
} }
@ -1269,7 +1275,7 @@ static int _main(int argc, char** argv) {
initPlugins(); initPlugins();
if (!op) { if (op == nullptr) {
throw UsageError("no operation specified"); throw UsageError("no operation specified");
} }

View file

@ -47,11 +47,11 @@ struct CmdBuild : MixDryRun, InstallablesCommand {
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]);
if (outLink != "") { if (!outLink.empty()) {
for (auto& output : b.outputs) { for (auto& output : b.outputs) {
if (auto store2 = store.dynamic_pointer_cast<LocalFSStore>()) { if (auto store2 = store.dynamic_pointer_cast<LocalFSStore>()) {
std::string symlink = outLink; std::string symlink = outLink;
if (i) { if (i != 0u) {
symlink += fmt("-%d", i); symlink += fmt("-%d", i);
} }
if (output.first != "out") { if (output.first != "out") {

View file

@ -80,9 +80,8 @@ bool MultiCommand::processFlag(Strings::iterator& pos, Strings::iterator end) {
bool MultiCommand::processArgs(const Strings& args, bool finish) { bool MultiCommand::processArgs(const Strings& args, bool finish) {
if (command) { if (command) {
return command->processArgs(args, finish); return command->processArgs(args, finish);
} else {
return Args::processArgs(args, finish);
} }
return Args::processArgs(args, finish);
} }
StoreCommand::StoreCommand() = default; StoreCommand::StoreCommand() = default;
@ -119,7 +118,7 @@ void StorePathsCommand::run(ref<Store> store) {
Paths storePaths; Paths storePaths;
if (all) { if (all) {
if (installables.size()) { if (!installables.empty() != 0u) {
throw UsageError("'--all' does not expect arguments"); throw UsageError("'--all' does not expect arguments");
} }
for (auto& p : store->queryAllValidPaths()) { for (auto& p : store->queryAllValidPaths()) {

View file

@ -7,7 +7,7 @@
using namespace nix; using namespace nix;
std::string formatProtocol(unsigned int proto) { std::string formatProtocol(unsigned int proto) {
if (proto) { if (proto != 0u) {
auto major = GET_PROTOCOL_MAJOR(proto) >> 8; auto major = GET_PROTOCOL_MAJOR(proto) >> 8;
auto minor = GET_PROTOCOL_MINOR(proto); auto minor = GET_PROTOCOL_MINOR(proto);
return (format("%1%.%2%") % major % minor).str(); return (format("%1%.%2%") % major % minor).str();
@ -41,7 +41,7 @@ struct CmdDoctor : StoreCommand {
} }
} }
bool checkNixInPath() { static bool checkNixInPath() {
PathSet dirs; PathSet dirs;
for (auto& dir : tokenizeString<Strings>(getEnv("PATH"), ":")) { for (auto& dir : tokenizeString<Strings>(getEnv("PATH"), ":")) {
@ -64,7 +64,7 @@ struct CmdDoctor : StoreCommand {
return true; return true;
} }
bool checkProfileRoots(ref<Store> store) { static bool checkProfileRoots(ref<Store> store) {
PathSet dirs; PathSet dirs;
for (auto& dir : tokenizeString<Strings>(getEnv("PATH"), ":")) { for (auto& dir : tokenizeString<Strings>(getEnv("PATH"), ":")) {
@ -106,7 +106,7 @@ struct CmdDoctor : StoreCommand {
return true; return true;
} }
bool checkStoreProtocol(unsigned int storeProto) { static bool checkStoreProtocol(unsigned int storeProto) {
unsigned int clientProto = GET_PROTOCOL_MAJOR(SERVE_PROTOCOL_VERSION) == unsigned int clientProto = GET_PROTOCOL_MAJOR(SERVE_PROTOCOL_VERSION) ==
GET_PROTOCOL_MAJOR(storeProto) GET_PROTOCOL_MAJOR(storeProto)
? SERVE_PROTOCOL_VERSION ? SERVE_PROTOCOL_VERSION

View file

@ -23,7 +23,7 @@ SourceExprCommand::SourceExprCommand() {
} }
Value* SourceExprCommand::getSourceExpr(EvalState& state) { Value* SourceExprCommand::getSourceExpr(EvalState& state) {
if (vSourceExpr) { if (vSourceExpr != nullptr) {
return vSourceExpr; return vSourceExpr;
} }
@ -31,7 +31,7 @@ Value* SourceExprCommand::getSourceExpr(EvalState& state) {
vSourceExpr = state.allocValue(); vSourceExpr = state.allocValue();
if (file != "") { if (!file.empty()) {
state.evalFile(lookupFileArg(state, file), *vSourceExpr); state.evalFile(lookupFileArg(state, file), *vSourceExpr);
} else { } else {
@ -46,7 +46,7 @@ Value* SourceExprCommand::getSourceExpr(EvalState& state) {
std::unordered_set<std::string> seen; std::unordered_set<std::string> seen;
auto addEntry = [&](const std::string& name) { auto addEntry = [&](const std::string& name) {
if (name == "") { if (name.empty()) {
return; return;
} }
if (!seen.insert(name).second) { if (!seen.insert(name).second) {
@ -135,7 +135,7 @@ struct InstallableValue : Installable {
drvPaths.insert(b.drvPath); drvPaths.insert(b.drvPath);
auto outputName = drv.queryOutputName(); auto outputName = drv.queryOutputName();
if (outputName == "") { if (outputName.empty()) {
throw Error("derivation '%s' lacks an 'outputName' attribute", throw Error("derivation '%s' lacks an 'outputName' attribute",
b.drvPath); b.drvPath);
} }
@ -153,9 +153,8 @@ struct InstallableValue : Installable {
b.outputs.insert(b2.outputs.begin(), b2.outputs.end()); b.outputs.insert(b2.outputs.begin(), b2.outputs.end());
} }
return {b}; return {b};
} else {
return res;
} }
return res;
} }
}; };
@ -204,7 +203,7 @@ static std::vector<std::shared_ptr<Installable>> parseInstallables(
std::vector<std::shared_ptr<Installable>> result; std::vector<std::shared_ptr<Installable>> result;
if (ss.empty() && useDefaultInstallables) { if (ss.empty() && useDefaultInstallables) {
if (cmd.file == "") { if (cmd.file.empty()) {
cmd.file = "."; cmd.file = ".";
} }
ss = {""}; ss = {""};
@ -222,7 +221,7 @@ static std::vector<std::shared_ptr<Installable>> parseInstallables(
} }
} }
else if (s == "" || std::regex_match(s, attrPathRegex)) { else if (s.empty() || std::regex_match(s, attrPathRegex)) {
result.push_back(std::make_shared<InstallableAttrPath>(cmd, s)); result.push_back(std::make_shared<InstallableAttrPath>(cmd, s));
} else { } else {
@ -254,7 +253,7 @@ Buildables build(ref<Store> store, RealiseMode mode,
for (auto& i : installables) { for (auto& i : installables) {
for (auto& b : i->toBuildables()) { for (auto& b : i->toBuildables()) {
if (b.drvPath != "") { if (!b.drvPath.empty()) {
StringSet outputNames; StringSet outputNames;
for (auto& output : b.outputs) { for (auto& output : b.outputs) {
outputNames.insert(output.first); outputNames.insert(output.first);

View file

@ -40,7 +40,7 @@ struct CmdLog : InstallableCommand {
RunPager pager; RunPager pager;
for (auto& sub : subs) { for (auto& sub : subs) {
auto log = b.drvPath != "" ? sub->getBuildLog(b.drvPath) : nullptr; auto log = !b.drvPath.empty() ? sub->getBuildLog(b.drvPath) : nullptr;
for (auto& output : b.outputs) { for (auto& output : b.outputs) {
if (log) { if (log) {
break; break;

View file

@ -27,14 +27,14 @@ namespace nix {
static bool haveInternet() { static bool haveInternet() {
struct ifaddrs* addrs; struct ifaddrs* addrs;
if (getifaddrs(&addrs)) { if (getifaddrs(&addrs) != 0) {
return true; return true;
} }
Finally free([&]() { freeifaddrs(addrs); }); Finally free([&]() { freeifaddrs(addrs); });
for (auto i = addrs; i; i = i->ifa_next) { for (auto i = addrs; i != nullptr; i = i->ifa_next) {
if (!i->ifa_addr) { if (i->ifa_addr == nullptr) {
continue; continue;
} }
if (i->ifa_addr->sa_family == AF_INET) { if (i->ifa_addr->sa_family == AF_INET) {

View file

@ -113,7 +113,7 @@ struct CmdPathInfo : StorePathsCommand, MixJSON {
if (info->ultimate) { if (info->ultimate) {
ss.push_back("ultimate"); ss.push_back("ultimate");
} }
if (info->ca != "") { if (!info->ca.empty()) {
ss.push_back("ca:" + info->ca); ss.push_back("ca:" + info->ca);
} }
for (auto& sig : info->sigs) { for (auto& sig : info->sigs) {

View file

@ -62,7 +62,7 @@ struct NixRepl {
~NixRepl(); ~NixRepl();
void mainLoop(const std::vector<std::string>& files); void mainLoop(const std::vector<std::string>& files);
StringSet completePrefix(string prefix); StringSet completePrefix(string prefix);
bool getLine(string& input, const std::string& prompt); static bool getLine(string& input, const std::string& prompt);
Path getDerivationPath(Value& v); Path getDerivationPath(Value& v);
bool processLine(string line); bool processLine(string line);
void loadFile(const Path& path); void loadFile(const Path& path);
@ -145,11 +145,12 @@ static char* completionCallback(char* s, int* match) {
if (possible.size() == 1) { if (possible.size() == 1) {
*match = 1; *match = 1;
auto* res = strdup(possible.begin()->c_str() + strlen(s)); auto* res = strdup(possible.begin()->c_str() + strlen(s));
if (!res) { if (res == nullptr) {
throw Error("allocation failure"); throw Error("allocation failure");
} }
return res; return res;
} else if (possible.size() > 1) { }
if (possible.size() > 1) {
auto checkAllHaveSameAt = [&](size_t pos) { auto checkAllHaveSameAt = [&](size_t pos) {
auto& first = *possible.begin(); auto& first = *possible.begin();
for (auto& p : possible) { for (auto& p : possible) {
@ -167,7 +168,7 @@ static char* completionCallback(char* s, int* match) {
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());
if (!res) { if (res == nullptr) {
throw Error("allocation failure"); throw Error("allocation failure");
} }
return res; return res;
@ -266,10 +267,9 @@ void NixRepl::mainLoop(const std::vector<std::string>& files) {
// For parse errors on incomplete input, we continue waiting for the // For parse errors on incomplete input, we continue waiting for the
// next line of input without clearing the input so far. // next line of input without clearing the input so far.
continue; continue;
} else {
LOG(ERROR) << error << (settings.showTrace ? e.prefix() : "")
<< e.msg();
} }
LOG(ERROR) << error << (settings.showTrace ? e.prefix() : "") << e.msg();
} catch (Error& e) { } catch (Error& e) {
LOG(ERROR) << error << (settings.showTrace ? e.prefix() : "") << e.msg(); LOG(ERROR) << error << (settings.showTrace ? e.prefix() : "") << e.msg();
} catch (Interrupted& e) { } catch (Interrupted& e) {
@ -284,29 +284,31 @@ void NixRepl::mainLoop(const std::vector<std::string>& files) {
} }
bool NixRepl::getLine(string& input, const std::string& prompt) { bool NixRepl::getLine(string& input, const std::string& prompt) {
struct sigaction act, old; struct sigaction act;
sigset_t savedSignalMask, set; struct sigaction old;
sigset_t savedSignalMask;
sigset_t set;
auto setupSignals = [&]() { auto setupSignals = [&]() {
act.sa_handler = sigintHandler; act.sa_handler = sigintHandler;
sigfillset(&act.sa_mask); sigfillset(&act.sa_mask);
act.sa_flags = 0; act.sa_flags = 0;
if (sigaction(SIGINT, &act, &old)) { if (sigaction(SIGINT, &act, &old) != 0) {
throw SysError("installing handler for SIGINT"); throw SysError("installing handler for SIGINT");
} }
sigemptyset(&set); sigemptyset(&set);
sigaddset(&set, SIGINT); sigaddset(&set, SIGINT);
if (sigprocmask(SIG_UNBLOCK, &set, &savedSignalMask)) { if (sigprocmask(SIG_UNBLOCK, &set, &savedSignalMask) != 0) {
throw SysError("unblocking SIGINT"); throw SysError("unblocking SIGINT");
} }
}; };
auto restoreSignals = [&]() { auto restoreSignals = [&]() {
if (sigprocmask(SIG_SETMASK, &savedSignalMask, nullptr)) { if (sigprocmask(SIG_SETMASK, &savedSignalMask, nullptr) != 0) {
throw SysError("restoring signals"); throw SysError("restoring signals");
} }
if (sigaction(SIGINT, &old, nullptr)) { if (sigaction(SIGINT, &old, nullptr) != 0) {
throw SysError("restoring handler for SIGINT"); throw SysError("restoring handler for SIGINT");
} }
}; };
@ -316,13 +318,13 @@ bool NixRepl::getLine(string& input, const std::string& prompt) {
Finally doFree([&]() { free(s); }); Finally doFree([&]() { free(s); });
restoreSignals(); restoreSignals();
if (g_signal_received) { if (g_signal_received != 0) {
g_signal_received = 0; g_signal_received = 0;
input.clear(); input.clear();
return true; return true;
} }
if (!s) { if (s == nullptr) {
return false; return false;
} }
input += s; input += s;
@ -334,7 +336,8 @@ StringSet NixRepl::completePrefix(string prefix) {
StringSet completions; StringSet completions;
size_t start = prefix.find_last_of(" \n\r\t(){}[]"); size_t start = prefix.find_last_of(" \n\r\t(){}[]");
std::string prev, cur; std::string prev;
std::string cur;
if (start == std::string::npos) { if (start == std::string::npos) {
prev = ""; prev = "";
cur = prefix; cur = prefix;
@ -343,13 +346,14 @@ StringSet NixRepl::completePrefix(string prefix) {
cur = std::string(prefix, start + 1); cur = std::string(prefix, start + 1);
} }
size_t slash, dot; size_t slash;
size_t dot;
if ((slash = cur.rfind('/')) != string::npos) { if ((slash = cur.rfind('/')) != string::npos) {
try { try {
auto dir = std::string(cur, 0, slash); auto dir = std::string(cur, 0, slash);
auto prefix2 = std::string(cur, slash + 1); auto prefix2 = std::string(cur, slash + 1);
for (auto& entry : readDirectory(dir == "" ? "/" : dir)) { for (auto& entry : readDirectory(dir.empty() ? "/" : dir)) {
if (entry.name[0] != '.' && hasPrefix(entry.name, prefix2)) { if (entry.name[0] != '.' && hasPrefix(entry.name, prefix2)) {
completions.insert(prev + dir + "/" + entry.name); completions.insert(prev + dir + "/" + entry.name);
} }
@ -418,7 +422,7 @@ static int runProgram(const string& program, const Strings& args) {
} }
bool isVarName(const string& s) { bool isVarName(const string& s) {
if (s.size() == 0) { if (s.empty()) {
return false; return false;
} }
char c = s[0]; char c = s[0];
@ -441,18 +445,19 @@ Path NixRepl::getDerivationPath(Value& v) {
"expression does not evaluate to a derivation, so I can't build it"); "expression does not evaluate to a derivation, so I can't build it");
} }
Path drvPath = drvInfo->queryDrvPath(); Path drvPath = drvInfo->queryDrvPath();
if (drvPath == "" || !state.store->isValidPath(drvPath)) { if (drvPath.empty() || !state.store->isValidPath(drvPath)) {
throw Error("expression did not evaluate to a valid derivation"); throw Error("expression did not evaluate to a valid derivation");
} }
return drvPath; return drvPath;
} }
bool NixRepl::processLine(string line) { bool NixRepl::processLine(string line) {
if (line == "") { if (line.empty()) {
return true; return true;
} }
string command, arg; string command;
string arg;
if (line[0] == ':') { if (line[0] == ':') {
size_t p = line.find_first_of(" \n\r\t"); size_t p = line.find_first_of(" \n\r\t");
@ -505,7 +510,9 @@ bool NixRepl::processLine(string line) {
std::cout << showType(v) << std::endl; std::cout << showType(v) << std::endl;
} else if (command == ":u") { } else if (command == ":u") {
Value v, f, result; Value v;
Value f;
Value result;
evalString(arg, v); evalString(arg, v);
evalString( evalString(
"drv: (import <nixpkgs> {}).runCommand \"shell\" { buildInputs = [ drv " "drv: (import <nixpkgs> {}).runCommand \"shell\" { buildInputs = [ drv "
@ -553,7 +560,7 @@ bool NixRepl::processLine(string line) {
else if (command == ":q" || command == ":quit") { else if (command == ":q" || command == ":quit") {
return false; return false;
} else if (command != "") { } else if (!command.empty()) {
throw Error(format("unknown command '%1%'") % command); throw Error(format("unknown command '%1%'") % command);
} else { } else {
@ -580,7 +587,8 @@ bool NixRepl::processLine(string line) {
void NixRepl::loadFile(const Path& path) { void NixRepl::loadFile(const Path& path) {
loadedFiles.remove(path); loadedFiles.remove(path);
loadedFiles.push_back(path); loadedFiles.push_back(path);
Value v, v2; Value v;
Value v2;
state.evalFile(lookupFileArg(state, path), v); state.evalFile(lookupFileArg(state, path), v);
state.autoCallFunction(*autoArgs, v, v2); state.autoCallFunction(*autoArgs, v, v2);
addAttrsToScope(v2); addAttrsToScope(v2);
@ -652,7 +660,7 @@ std::ostream& NixRepl::printValue(std::ostream& str, Value& v,
std::ostream& printStringValue(std::ostream& str, const char* string) { std::ostream& printStringValue(std::ostream& str, const char* string) {
str << "\""; str << "\"";
for (const char* i = string; *i; i++) { for (const char* i = string; *i != 0; i++) {
if (*i == '\"' || *i == '\\') { if (*i == '\"' || *i == '\\') {
str << "\\" << *i; str << "\\" << *i;
} else if (*i == '\n') { } else if (*i == '\n') {

View file

@ -96,7 +96,7 @@ struct CmdRun : InstallablesCommand {
std::map<std::string, std::string> kept; std::map<std::string, std::string> kept;
for (auto& var : keep) { for (auto& var : keep) {
auto s = getenv(var.c_str()); auto s = getenv(var.c_str());
if (s) { if (s != nullptr) {
kept[var] = s; kept[var] = s;
} }
} }
@ -133,9 +133,7 @@ struct CmdRun : InstallablesCommand {
continue; continue;
} }
if (true) { { unixPath.push_front(path + "/bin"); }
unixPath.push_front(path + "/bin");
}
auto propPath = path + "/nix-support/propagated-user-env-packages"; auto propPath = path + "/nix-support/propagated-user-env-packages";
if (accessor->stat(propPath).type == FSAccessor::tRegular) { if (accessor->stat(propPath).type == FSAccessor::tRegular) {
@ -249,7 +247,7 @@ void chrootHelper(int argc, char** argv) {
} }
char* cwd = getcwd(nullptr, 0); char* cwd = getcwd(nullptr, 0);
if (!cwd) { if (cwd == nullptr) {
throw SysError("getting current directory"); throw SysError("getting current directory");
} }
Finally freeCwd([&]() { free(cwd); }); Finally freeCwd([&]() { free(cwd); });

View file

@ -160,11 +160,11 @@ struct CmdSearch : SourceExprCommand, MixJSON {
} }
} }
if (cache) { if (cache != nullptr) {
cache->attr("type", "derivation"); cache->attr("type", "derivation");
cache->attr("name", drv.queryName()); cache->attr("name", drv.queryName());
cache->attr("system", drv.querySystem()); cache->attr("system", drv.querySystem());
if (description != "") { if (!description.empty()) {
auto meta(cache->object("meta")); auto meta(cache->object("meta"));
meta.attr("description", description); meta.attr("description", description);
} }
@ -190,11 +190,12 @@ struct CmdSearch : SourceExprCommand, MixJSON {
for (auto& i : *v->attrs) { for (auto& i : *v->attrs) {
auto cache2 = auto cache2 =
cache ? std::make_unique<JSONObject>(cache->object(i.name)) cache != nullptr
: nullptr; ? std::make_unique<JSONObject>(cache->object(i.name))
: nullptr;
doExpr(i.value, doExpr(i.value,
attrPath == "" ? (std::string)i.name attrPath.empty() ? (std::string)i.name
: attrPath + "." + (std::string)i.name, : attrPath + "." + (std::string)i.name,
toplevel2 || fromCache, cache2 ? cache2.get() : nullptr); toplevel2 || fromCache, cache2 ? cache2.get() : nullptr);
} }
} }
@ -256,7 +257,7 @@ struct CmdSearch : SourceExprCommand, MixJSON {
} }
} }
if (results.size() == 0) { if (results.empty()) {
throw Error("no results for the given search term(s)!"); throw Error("no results for the given search term(s)!");
} }

View file

@ -63,7 +63,7 @@ struct CmdShowDerivation : InstallablesCommand {
for (auto& output : drv.outputs) { for (auto& output : drv.outputs) {
auto outputObj(outputsObj.object(output.first)); auto outputObj(outputsObj.object(output.first));
outputObj.attr("path", output.second.path); outputObj.attr("path", output.second.path);
if (output.second.hash != "") { if (!output.second.hash.empty()) {
outputObj.attr("hashAlgo", output.second.hashAlgo); outputObj.attr("hashAlgo", output.second.hashAlgo);
outputObj.attr("hash", output.second.hash); outputObj.attr("hash", output.second.hash);
} }

View file

@ -71,7 +71,7 @@ struct CmdCopySigs : StorePathsCommand {
} }
for (auto& sig : info2->sigs) { for (auto& sig : info2->sigs) {
if (!info->sigs.count(sig)) { if (info->sigs.count(sig) == 0u) {
newSigs.insert(sig); newSigs.insert(sig);
} }
} }
@ -132,7 +132,7 @@ struct CmdSignPaths : StorePathsCommand {
info2.sign(secretKey); info2.sign(secretKey);
assert(!info2.sigs.empty()); assert(!info2.sigs.empty());
if (!info->sigs.count(*info2.sigs.begin())) { if (info->sigs.count(*info2.sigs.begin()) == 0u) {
store->addSignatures(storePath, info2.sigs); store->addSignatures(storePath, info2.sigs);
added++; added++;
} }

View file

@ -52,7 +52,7 @@ struct CmdUpgradeNix : MixDryRun, StoreCommand {
void run(ref<Store> store) override { void run(ref<Store> store) override {
evalSettings.pureEval = true; evalSettings.pureEval = true;
if (profileDir == "") { if (profileDir.empty()) {
profileDir = getProfileDir(store); profileDir = getProfileDir(store);
} }
@ -97,7 +97,7 @@ struct CmdUpgradeNix : MixDryRun, StoreCommand {
} }
/* Return the profile in which Nix is installed. */ /* Return the profile in which Nix is installed. */
Path getProfileDir(ref<Store> store) { static Path getProfileDir(ref<Store> store) {
Path where; Path where;
for (auto& dir : tokenizeString<Strings>(getEnv("PATH"), ":")) { for (auto& dir : tokenizeString<Strings>(getEnv("PATH"), ":")) {
@ -107,7 +107,7 @@ struct CmdUpgradeNix : MixDryRun, StoreCommand {
} }
} }
if (where == "") { if (where.empty()) {
throw Error( throw Error(
"couldn't figure out how Nix is installed, so I can't upgrade it"); "couldn't figure out how Nix is installed, so I can't upgrade it");
} }

View file

@ -94,7 +94,7 @@ struct CmdVerify : StorePathsCommand {
if (!noTrust) { if (!noTrust) {
bool good = false; bool good = false;
if (info->ultimate && !sigsNeeded) { if (info->ultimate && (sigsNeeded == 0u)) {
good = true; good = true;
} else { } else {
@ -104,7 +104,7 @@ struct CmdVerify : StorePathsCommand {
auto doSigs = [&](StringSet sigs) { auto doSigs = [&](StringSet sigs) {
for (auto sig : sigs) { for (auto sig : sigs) {
if (sigsSeen.count(sig)) { if (sigsSeen.count(sig) != 0u) {
continue; continue;
} }
sigsSeen.insert(sig); sigsSeen.insert(sig);
@ -162,7 +162,8 @@ struct CmdVerify : StorePathsCommand {
pool.process(); pool.process();
throw Exit((corrupted ? 1 : 0) | (untrusted ? 2 : 0) | (failed ? 4 : 0)); throw Exit((corrupted != 0u ? 1 : 0) | (untrusted != 0u ? 2 : 0) |
(failed != 0u ? 4 : 0));
} }
}; };

View file

@ -18,7 +18,7 @@ static std::string hilite(const std::string& s, size_t pos, size_t len,
static std::string filterPrintable(const std::string& s) { static std::string filterPrintable(const std::string& s) {
std::string res; std::string res;
for (char c : s) { for (char c : s) {
res += isprint(c) ? c : '.'; res += isprint(c) != 0 ? c : '.';
} }
return res; return res;
} }
@ -70,7 +70,7 @@ struct CmdWhyDepends : SourceExprCommand {
PathSet closure; PathSet closure;
store->computeFSClosure({packagePath}, closure, false, false); store->computeFSClosure({packagePath}, closure, false, false);
if (!closure.count(dependencyPath)) { if (closure.count(dependencyPath) == 0u) {
LOG(WARNING) << "'" << package->what() << "' does not depend on '" LOG(WARNING) << "'" << package->what() << "' does not depend on '"
<< dependency->what() << "'"; << dependency->what() << "'";
return; return;
@ -146,7 +146,7 @@ struct CmdWhyDepends : SourceExprCommand {
assert(node.dist != inf); assert(node.dist != inf);
std::cout << fmt("%s%s%s%s" ANSI_NORMAL "\n", firstPad, std::cout << fmt("%s%s%s%s" ANSI_NORMAL "\n", firstPad,
node.visited ? "\e[38;5;244m" : "", node.visited ? "\e[38;5;244m" : "",
firstPad != "" ? "=> " : "", node.path); !firstPad.empty() ? "=> " : "", node.path);
if (node.path == dependencyPath && !all && if (node.path == dependencyPath && !all &&
packagePath != dependencyPath) { packagePath != dependencyPath) {