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

This applies the performance fixes listed here:

https://clang.llvm.org/extra/clang-tidy/checks/list.html
This commit is contained in:
Vincent Ambo 2020-05-20 22:58:43 +01:00
parent 689ef502f5
commit 43677021e3
60 changed files with 189 additions and 166 deletions

View file

@ -29,7 +29,7 @@ MixEvalArgs::MixEvalArgs() {
"add a path to the list of locations used to look up <...> file " "add a path to the list of locations used to look up <...> file "
"names") "names")
.label("path") .label("path")
.handler([&](std::string s) { searchPath.push_back(s); }); .handler([&](const std::string& s) { searchPath.push_back(s); });
} }
Bindings* MixEvalArgs::getAutoArgs(EvalState& state) { Bindings* MixEvalArgs::getAutoArgs(EvalState& state) {

View file

@ -298,7 +298,7 @@ static Strings parseNixPath(const string& s) {
return res; return res;
} }
EvalState::EvalState(const Strings& _searchPath, ref<Store> store) EvalState::EvalState(const Strings& _searchPath, const ref<Store>& store)
: sWith(symbols.create("<with>")), : sWith(symbols.create("<with>")),
sOutPath(symbols.create("outPath")), sOutPath(symbols.create("outPath")),
sDrvPath(symbols.create("drvPath")), sDrvPath(symbols.create("drvPath")),

View file

@ -105,7 +105,7 @@ class EvalState {
std::unordered_map<Path, Path> resolvedPaths; std::unordered_map<Path, Path> resolvedPaths;
public: public:
EvalState(const Strings& _searchPath, ref<Store> store); EvalState(const Strings& _searchPath, const ref<Store>& store);
~EvalState(); ~EvalState();
void addToSearchPath(const string& s); void addToSearchPath(const string& s);

View file

@ -15,7 +15,7 @@ namespace nix {
DrvInfo::DrvInfo(EvalState& state, string attrPath, Bindings* attrs) DrvInfo::DrvInfo(EvalState& state, string attrPath, Bindings* attrs)
: state(&state), attrs(attrs), attrPath(std::move(attrPath)) {} : state(&state), attrs(attrs), attrPath(std::move(attrPath)) {}
DrvInfo::DrvInfo(EvalState& state, ref<Store> store, DrvInfo::DrvInfo(EvalState& state, const ref<Store>& store,
const std::string& drvPathWithOutputs) const std::string& drvPathWithOutputs)
: state(&state), attrPath("") { : state(&state), attrPath("") {
auto spec = parseDrvPathWithOutputs(drvPathWithOutputs); auto spec = parseDrvPathWithOutputs(drvPathWithOutputs);

View file

@ -34,7 +34,7 @@ struct DrvInfo {
DrvInfo(EvalState& state) : state(&state){}; DrvInfo(EvalState& state) : state(&state){};
DrvInfo(EvalState& state, string attrPath, Bindings* attrs); DrvInfo(EvalState& state, string attrPath, Bindings* attrs);
DrvInfo(EvalState& state, ref<Store> store, DrvInfo(EvalState& state, const ref<Store>& store,
const std::string& drvPathWithOutputs); const std::string& drvPathWithOutputs);
string queryName() const; string queryName() const;

View file

@ -34,7 +34,7 @@ namespace nix {
name>. */ name>. */
std::pair<string, string> decodeContext(const string& s) { std::pair<string, string> decodeContext(const string& s) {
if (s.at(0) == '!') { if (s.at(0) == '!') {
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));
} }
@ -2172,7 +2172,7 @@ static void prim_splitVersion(EvalState& state, const Pos& pos, Value** args,
unsigned int n = 0; unsigned int n = 0;
for (auto& component : components) { for (auto& component : components) {
auto listElem = v.listElems()[n++] = state.allocValue(); auto listElem = v.listElems()[n++] = state.allocValue();
mkString(*listElem, std::move(component)); mkString(*listElem, component);
} }
} }
@ -2246,7 +2246,8 @@ 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(const std::string& name, size_t arity,
PrimOpFun fun) {
if (primOps == nullptr) { if (primOps == nullptr) {
primOps = new PrimOps; primOps = new PrimOps;
} }

View file

@ -11,7 +11,7 @@ struct RegisterPrimOp {
/* You can register a constant by passing an arity of 0. fun /* You can register a constant by passing an arity of 0. fun
will get called during EvalState initialization, so there will get called during EvalState initialization, so there
may be primops not yet added and builtins is not yet sorted. */ may be primops not yet added and builtins is not yet sorted. */
RegisterPrimOp(std::string name, size_t arity, PrimOpFun fun); RegisterPrimOp(const std::string& name, size_t arity, PrimOpFun fun);
}; };
/* These primops are disabled without enableNativeCode, but plugins /* These primops are disabled without enableNativeCode, but plugins

View file

@ -26,7 +26,7 @@ MixCommonArgs::MixCommonArgs(const string& programName)
.shortName('j') .shortName('j')
.label("jobs") .label("jobs")
.description("maximum number of parallel builds") .description("maximum number of parallel builds")
.handler([=](std::string s) { settings.set("max-jobs", s); }); .handler([=](const std::string& s) { settings.set("max-jobs", s); });
std::string cat = "config"; std::string cat = "config";
globalConfig.convertToArgs(*this, cat); globalConfig.convertToArgs(*this, cat);

View file

@ -36,7 +36,7 @@ void printGCWarning() {
} }
} }
void printMissing(ref<Store> store, const PathSet& paths) { void printMissing(const ref<Store>& store, const PathSet& paths) {
unsigned long long downloadSize; unsigned long long downloadSize;
unsigned long long narSize; unsigned long long narSize;
PathSet willBuild; PathSet willBuild;
@ -48,7 +48,7 @@ void printMissing(ref<Store> store, const PathSet& paths) {
narSize); narSize);
} }
void printMissing(ref<Store> store, const PathSet& willBuild, void printMissing(const ref<Store>& store, const PathSet& willBuild,
const PathSet& willSubstitute, const PathSet& unknown, const PathSet& willSubstitute, const PathSet& unknown,
unsigned long long downloadSize, unsigned long long narSize) { unsigned long long downloadSize, unsigned long long narSize) {
if (!willBuild.empty()) { if (!willBuild.empty()) {
@ -260,14 +260,15 @@ void parseCmdLine(
int argc, char** argv, int argc, char** argv,
std::function<bool(Strings::iterator& arg, const Strings::iterator& end)> std::function<bool(Strings::iterator& arg, const Strings::iterator& end)>
parseArg) { parseArg) {
parseCmdLine(baseNameOf(argv[0]), argvToStrings(argc, argv), parseArg); parseCmdLine(baseNameOf(argv[0]), argvToStrings(argc, argv),
std::move(parseArg));
} }
void parseCmdLine( void parseCmdLine(
const string& programName, const Strings& args, const string& programName, const Strings& args,
std::function<bool(Strings::iterator& arg, const Strings::iterator& end)> std::function<bool(Strings::iterator& arg, const Strings::iterator& end)>
parseArg) { parseArg) {
LegacyArgs(programName, parseArg).parseCmdline(args); LegacyArgs(programName, std::move(parseArg)).parseCmdline(args);
} }
void printVersion(const string& programName) { void printVersion(const string& programName) {
@ -298,7 +299,8 @@ void showManPage(const string& name) {
throw SysError(format("command 'man %1%' failed") % name.c_str()); throw SysError(format("command 'man %1%' failed") % name.c_str());
} }
int handleExceptions(const string& programName, std::function<void()> fun) { int handleExceptions(const string& programName,
const std::function<void()>& fun) {
ReceiveInterrupts receiveInterrupts; // FIXME: need better place for this ReceiveInterrupts receiveInterrupts; // FIXME: need better place for this
string error = ANSI_RED "error:" ANSI_NORMAL " "; string error = ANSI_RED "error:" ANSI_NORMAL " ";

View file

@ -18,7 +18,8 @@ class Exit : public std::exception {
virtual ~Exit(); virtual ~Exit();
}; };
int handleExceptions(const string& programName, std::function<void()> fun); int handleExceptions(const string& programName,
const std::function<void()>& fun);
/* Don't forget to call initPlugins() after settings are initialized! */ /* Don't forget to call initPlugins() after settings are initialized! */
void initNix(); void initNix();
@ -40,9 +41,9 @@ void printGCWarning();
class Store; class Store;
void printMissing(ref<Store> store, const PathSet& paths); void printMissing(const ref<Store>& store, const PathSet& paths);
void printMissing(ref<Store> store, const PathSet& willBuild, void printMissing(const ref<Store>& store, const PathSet& willBuild,
const PathSet& willSubstitute, const PathSet& unknown, const PathSet& willSubstitute, const PathSet& unknown,
unsigned long long downloadSize, unsigned long long narSize); unsigned long long downloadSize, unsigned long long narSize);

View file

@ -98,7 +98,7 @@ Path BinaryCacheStore::narInfoFileFor(const Path& storePath) {
return storePathToHash(storePath) + ".narinfo"; return storePathToHash(storePath) + ".narinfo";
} }
void BinaryCacheStore::writeNarInfo(ref<NarInfo> narInfo) { void BinaryCacheStore::writeNarInfo(const ref<NarInfo>& narInfo) {
auto narInfoFile = narInfoFileFor(narInfo->path); auto narInfoFile = narInfoFileFor(narInfo->path);
upsertFile(narInfoFile, narInfo->to_string(), "text/x-nix-narinfo"); upsertFile(narInfoFile, narInfo->to_string(), "text/x-nix-narinfo");

View file

@ -65,7 +65,7 @@ class BinaryCacheStore : public Store {
std::string narInfoFileFor(const Path& storePath); std::string narInfoFileFor(const Path& storePath);
void writeNarInfo(ref<NarInfo> narInfo); void writeNarInfo(const ref<NarInfo>& narInfo);
public: public:
bool isValidPathUncached(const Path& path) override; bool isValidPathUncached(const Path& path) override;

View file

@ -145,7 +145,7 @@ class Goal : public std::enable_shared_from_this<Goal> {
public: public:
virtual void work() = 0; virtual void work() = 0;
void addWaitee(GoalPtr waitee); void addWaitee(const GoalPtr& waitee);
virtual void waiteeDone(GoalPtr waitee, ExitCode result); virtual void waiteeDone(GoalPtr waitee, ExitCode result);
@ -280,10 +280,10 @@ class Worker {
RepairFlag repair = NoRepair); RepairFlag repair = NoRepair);
/* Remove a dead goal. */ /* Remove a dead goal. */
void removeGoal(GoalPtr goal); void removeGoal(const GoalPtr& goal);
/* Wake up a goal (i.e., there is something for it to do). */ /* Wake up a goal (i.e., there is something for it to do). */
void wakeUp(GoalPtr goal); void wakeUp(const GoalPtr& goal);
/* Return the number of local build and substitution processes /* Return the number of local build and substitution processes
currently running (but not remote builds via the build currently running (but not remote builds via the build
@ -292,7 +292,7 @@ class Worker {
/* Registers a running child process. `inBuildSlot' means that /* Registers a running child process. `inBuildSlot' means that
the process counts towards the jobs limit. */ the process counts towards the jobs limit. */
void childStarted(GoalPtr goal, const set<int>& fds, bool inBuildSlot, void childStarted(const GoalPtr& goal, const set<int>& fds, bool inBuildSlot,
bool respectTimeouts); bool respectTimeouts);
/* Unregisters a running child process. `wakeSleepers' should be /* Unregisters a running child process. `wakeSleepers' should be
@ -303,7 +303,7 @@ class Worker {
/* Put `goal' to sleep until a build slot becomes available (which /* Put `goal' to sleep until a build slot becomes available (which
might be right away). */ might be right away). */
void waitForBuildSlot(GoalPtr goal); void waitForBuildSlot(const GoalPtr& goal);
/* Wait for any goal to finish. Pretty indiscriminate way to /* Wait for any goal to finish. Pretty indiscriminate way to
wait for some resource that some other goal is holding. */ wait for some resource that some other goal is holding. */
@ -332,7 +332,7 @@ class Worker {
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
void addToWeakGoals(WeakGoals& goals, GoalPtr p) { void addToWeakGoals(WeakGoals& goals, const GoalPtr& p) {
// FIXME: necessary? // FIXME: necessary?
// FIXME: O(n) // FIXME: O(n)
for (auto& i : goals) { for (auto& i : goals) {
@ -343,7 +343,7 @@ void addToWeakGoals(WeakGoals& goals, GoalPtr p) {
goals.push_back(p); goals.push_back(p);
} }
void Goal::addWaitee(GoalPtr waitee) { void Goal::addWaitee(const GoalPtr& waitee) {
waitees.insert(waitee); waitees.insert(waitee);
addToWeakGoals(waitee->waiters, shared_from_this()); addToWeakGoals(waitee->waiters, shared_from_this());
} }
@ -445,7 +445,9 @@ void handleDiffHook(uid_t uid, uid_t gid, Path tryA, Path tryB, Path drvPath,
auto diffHook = settings.diffHook; auto diffHook = settings.diffHook;
if (diffHook != "" && settings.runDiffHook) { if (diffHook != "" && settings.runDiffHook) {
try { try {
RunOptions diffHookOptions(diffHook, {tryA, tryB, drvPath, tmpDir}); RunOptions diffHookOptions(
diffHook, {std::move(tryA), std::move(tryB), std::move(drvPath),
std::move(tmpDir)});
diffHookOptions.searchPath = true; diffHookOptions.searchPath = true;
diffHookOptions.uid = uid; diffHookOptions.uid = uid;
diffHookOptions.gid = gid; diffHookOptions.gid = gid;
@ -979,7 +981,7 @@ class DerivationGoal : public Goal {
void done(BuildResult::Status status, const string& msg = ""); void done(BuildResult::Status status, const string& msg = "");
PathSet exportReferences(PathSet storePaths); PathSet exportReferences(const PathSet& storePaths);
}; };
const Path DerivationGoal::homeDir = "/homeless-shelter"; const Path DerivationGoal::homeDir = "/homeless-shelter";
@ -1520,7 +1522,7 @@ void DerivationGoal::tryToBuild() {
started(); started();
} }
void replaceValidPath(const Path& storePath, const Path tmpPath) { void replaceValidPath(const Path& storePath, const Path& tmpPath) {
/* We can't atomically replace storePath (the original) with /* We can't atomically replace storePath (the original) with
tmpPath (the replacement), so we have to move it out of the tmpPath (the replacement), so we have to move it out of the
way first. We'd better not be interrupted here, because if way first. We'd better not be interrupted here, because if
@ -1840,7 +1842,7 @@ int childEntry(void* arg) {
return 1; return 1;
} }
PathSet DerivationGoal::exportReferences(PathSet storePaths) { PathSet DerivationGoal::exportReferences(const PathSet& storePaths) {
PathSet paths; PathSet paths;
for (auto storePath : storePaths) { for (auto storePath : storePaths) {
@ -4455,7 +4457,7 @@ GoalPtr Worker::makeSubstitutionGoal(const Path& path, RepairFlag repair) {
return goal; return goal;
} }
static void removeGoal(GoalPtr goal, WeakGoalMap& goalMap) { static void removeGoal(const GoalPtr& goal, WeakGoalMap& goalMap) {
/* !!! inefficient */ /* !!! inefficient */
for (auto i = goalMap.begin(); i != goalMap.end();) { for (auto i = goalMap.begin(); i != goalMap.end();) {
if (i->second.lock() == goal) { if (i->second.lock() == goal) {
@ -4469,7 +4471,7 @@ static void removeGoal(GoalPtr goal, WeakGoalMap& goalMap) {
} }
} }
void Worker::removeGoal(GoalPtr goal) { void Worker::removeGoal(const GoalPtr& goal) {
nix::removeGoal(goal, derivationGoals); nix::removeGoal(goal, derivationGoals);
nix::removeGoal(goal, substitutionGoals); nix::removeGoal(goal, substitutionGoals);
if (topGoals.find(goal) != topGoals.end()) { if (topGoals.find(goal) != topGoals.end()) {
@ -4492,15 +4494,15 @@ void Worker::removeGoal(GoalPtr goal) {
waitingForAnyGoal.clear(); waitingForAnyGoal.clear();
} }
void Worker::wakeUp(GoalPtr goal) { void Worker::wakeUp(const GoalPtr& goal) {
goal->trace("woken up"); goal->trace("woken up");
addToWeakGoals(awake, goal); addToWeakGoals(awake, goal);
} }
unsigned Worker::getNrLocalBuilds() { return nrLocalBuilds; } unsigned Worker::getNrLocalBuilds() { return nrLocalBuilds; }
void Worker::childStarted(GoalPtr goal, const set<int>& fds, bool inBuildSlot, void Worker::childStarted(const GoalPtr& goal, const set<int>& fds,
bool respectTimeouts) { bool inBuildSlot, bool respectTimeouts) {
Child child; Child child;
child.goal = goal; child.goal = goal;
child.goal2 = goal.get(); child.goal2 = goal.get();
@ -4542,7 +4544,7 @@ void Worker::childTerminated(Goal* goal, bool wakeSleepers) {
} }
} }
void Worker::waitForBuildSlot(GoalPtr goal) { void Worker::waitForBuildSlot(const GoalPtr& goal) {
DLOG(INFO) << "wait for build slot"; DLOG(INFO) << "wait for build slot";
if (getNrLocalBuilds() < settings.maxBuildJobs) { if (getNrLocalBuilds() < settings.maxBuildJobs) {
wakeUp(goal); /* we can do it right away */ wakeUp(goal); /* we can do it right away */
@ -4553,12 +4555,12 @@ void Worker::waitForBuildSlot(GoalPtr goal) {
void Worker::waitForAnyGoal(GoalPtr goal) { void Worker::waitForAnyGoal(GoalPtr goal) {
DLOG(INFO) << "wait for any goal"; DLOG(INFO) << "wait for any goal";
addToWeakGoals(waitingForAnyGoal, goal); addToWeakGoals(waitingForAnyGoal, std::move(goal));
} }
void Worker::waitForAWhile(GoalPtr goal) { void Worker::waitForAWhile(GoalPtr goal) {
DLOG(INFO) << "wait for a while"; DLOG(INFO) << "wait for a while";
addToWeakGoals(waitingForAWhile, goal); addToWeakGoals(waitingForAWhile, std::move(goal));
} }
void Worker::run(const Goals& _topGoals) { void Worker::run(const Goals& _topGoals) {

View file

@ -104,12 +104,12 @@ PublicKeys getDefaultPublicKeys() {
// FIXME: filter duplicates // FIXME: filter duplicates
for (auto s : settings.trustedPublicKeys.get()) { for (const auto& s : settings.trustedPublicKeys.get()) {
PublicKey key(s); PublicKey key(s);
publicKeys.emplace(key.name, key); publicKeys.emplace(key.name, key);
} }
for (auto secretKeyFile : settings.secretKeyFiles.get()) { for (const auto& secretKeyFile : settings.secretKeyFiles.get()) {
try { try {
SecretKey secretKey(readFile(secretKeyFile)); SecretKey secretKey(readFile(secretKeyFile));
publicKeys.emplace(secretKey.name, secretKey.toPublicKey()); publicKeys.emplace(secretKey.name, secretKey.toPublicKey());

View file

@ -38,7 +38,7 @@ bool BasicDerivation::isBuiltin() const {
return string(builder, 0, 8) == "builtin:"; return string(builder, 0, 8) == "builtin:";
} }
Path writeDerivation(ref<Store> store, const Derivation& drv, Path writeDerivation(const ref<Store>& store, const Derivation& drv,
const string& name, RepairFlag repair) { const string& name, RepairFlag repair) {
PathSet references; PathSet references;
references.insert(drv.inputSrcs.begin(), drv.inputSrcs.end()); references.insert(drv.inputSrcs.begin(), drv.inputSrcs.end());
@ -355,7 +355,7 @@ 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 == std::string::npos return n == std::string::npos
? DrvPathWithOutputs(s, std::set<string>()) ? DrvPathWithOutputs(s, std::set<string>())
: DrvPathWithOutputs( : DrvPathWithOutputs(

View file

@ -67,7 +67,7 @@ struct Derivation : BasicDerivation {
class Store; class Store;
/* Write a derivation to the Nix store, and return its path. */ /* Write a derivation to the Nix store, and return its path. */
Path writeDerivation(ref<Store> store, const Derivation& drv, Path writeDerivation(const ref<Store>& store, const Derivation& drv,
const string& name, RepairFlag repair = NoRepair); const string& name, RepairFlag repair = NoRepair);
/* Read a derivation from a file. */ /* Read a derivation from a file. */

View file

@ -130,7 +130,7 @@ struct CurlDownloader : public Downloader {
} }
} }
void failEx(std::exception_ptr ex) { void failEx(const std::exception_ptr& ex) {
assert(!done); assert(!done);
done = true; done = true;
callback.rethrow(ex); callback.rethrow(ex);
@ -663,7 +663,7 @@ struct CurlDownloader : public Downloader {
} }
} }
void enqueueItem(std::shared_ptr<DownloadItem> item) { void enqueueItem(const std::shared_ptr<DownloadItem>& item) {
if (item->request.data && !hasPrefix(item->request.uri, "http://") && if (item->request.data && !hasPrefix(item->request.uri, "http://") &&
!hasPrefix(item->request.uri, "https://")) { !hasPrefix(item->request.uri, "https://")) {
throw nix::Error("uploading to '%s' is not supported", item->request.uri); throw nix::Error("uploading to '%s' is not supported", item->request.uri);
@ -858,7 +858,7 @@ void Downloader::download(DownloadRequest&& request, Sink& sink) {
} }
CachedDownloadResult Downloader::downloadCached( CachedDownloadResult Downloader::downloadCached(
ref<Store> store, const CachedDownloadRequest& request) { const ref<Store>& store, const CachedDownloadRequest& request) {
auto url = resolveUri(request.uri); auto url = resolveUri(request.uri);
auto name = request.name; auto name = request.name;

View file

@ -108,7 +108,7 @@ struct Downloader {
and is more recent than tarball-ttl seconds. Otherwise, and is more recent than tarball-ttl seconds. Otherwise,
use the recorded ETag to verify if the server has a more use the recorded ETag to verify if the server has a more
recent version, and if so, download it to the Nix store. */ recent version, and if so, download it to the Nix store. */
CachedDownloadResult downloadCached(ref<Store> store, CachedDownloadResult downloadCached(const ref<Store>& store,
const CachedDownloadRequest& request); const CachedDownloadRequest& request);
enum Error { NotFound, Forbidden, Misc, Transient, Interrupted }; enum Error { NotFound, Forbidden, Misc, Transient, Interrupted };

View file

@ -55,7 +55,8 @@ void Store::exportPath(const Path& path, Sink& sink) {
<< 0; << 0;
} }
Paths Store::importPaths(Source& source, std::shared_ptr<FSAccessor> accessor, Paths Store::importPaths(Source& source,
const std::shared_ptr<FSAccessor>& accessor,
CheckSigsFlag checkSigs) { CheckSigsFlag checkSigs) {
Paths res; Paths res;
while (true) { while (true) {

View file

@ -149,17 +149,18 @@ void BaseSetting<SandboxMode>::convertToArg(Args& args,
args.mkFlag() args.mkFlag()
.longName(name) .longName(name)
.description("Enable sandboxing.") .description("Enable sandboxing.")
.handler([=](std::vector<std::string> ss) { override(smEnabled); }) .handler([=](const std::vector<std::string>& ss) { override(smEnabled); })
.category(category); .category(category);
args.mkFlag() args.mkFlag()
.longName("no-" + name) .longName("no-" + name)
.description("Disable sandboxing.") .description("Disable sandboxing.")
.handler([=](std::vector<std::string> ss) { override(smDisabled); }) .handler(
[=](const std::vector<std::string>& ss) { override(smDisabled); })
.category(category); .category(category);
args.mkFlag() args.mkFlag()
.longName("relaxed-" + name) .longName("relaxed-" + name)
.description("Enable sandboxing, but allow builds to disable it.") .description("Enable sandboxing, but allow builds to disable it.")
.handler([=](std::vector<std::string> ss) { override(smRelaxed); }) .handler([=](const std::vector<std::string>& ss) { override(smRelaxed); })
.category(category); .category(category);
} }

View file

@ -12,7 +12,7 @@ LocalFSStore::LocalFSStore(const Params& params) : Store(params) {}
struct LocalStoreAccessor : public FSAccessor { struct LocalStoreAccessor : public FSAccessor {
ref<LocalFSStore> store; ref<LocalFSStore> store;
explicit LocalStoreAccessor(ref<LocalFSStore> store) : store(store) {} explicit LocalStoreAccessor(const ref<LocalFSStore>& store) : store(store) {}
Path toRealPath(const Path& path) { Path toRealPath(const Path& path) {
Path storePath = store->toStorePath(path); Path storePath = store->toStorePath(path);

View file

@ -9,12 +9,12 @@
namespace nix { namespace nix {
Machine::Machine(decltype(storeUri) storeUri, decltype(systemTypes) systemTypes, Machine::Machine(decltype(storeUri)& storeUri,
decltype(sshKey) sshKey, decltype(maxJobs) maxJobs, decltype(systemTypes)& systemTypes, decltype(sshKey)& sshKey,
decltype(speedFactor) speedFactor, decltype(maxJobs) maxJobs, decltype(speedFactor) speedFactor,
decltype(supportedFeatures) supportedFeatures, decltype(supportedFeatures)& supportedFeatures,
decltype(mandatoryFeatures) mandatoryFeatures, decltype(mandatoryFeatures)& mandatoryFeatures,
decltype(sshPublicHostKey) sshPublicHostKey) decltype(sshPublicHostKey)& sshPublicHostKey)
: storeUri( : storeUri(
// Backwards compatibility: if the URI is a hostname, // Backwards compatibility: if the URI is a hostname,
// prepend ssh://. // prepend ssh://.

View file

@ -19,12 +19,12 @@ struct Machine {
bool mandatoryMet(const std::set<string>& features) const; bool mandatoryMet(const std::set<string>& features) const;
Machine(decltype(storeUri) storeUri, decltype(systemTypes) systemTypes, Machine(decltype(storeUri)& storeUri, decltype(systemTypes)& systemTypes,
decltype(sshKey) sshKey, decltype(maxJobs) maxJobs, decltype(sshKey)& sshKey, decltype(maxJobs) maxJobs,
decltype(speedFactor) speedFactor, decltype(speedFactor) speedFactor,
decltype(supportedFeatures) supportedFeatures, decltype(supportedFeatures)& supportedFeatures,
decltype(mandatoryFeatures) mandatoryFeatures, decltype(mandatoryFeatures)& mandatoryFeatures,
decltype(sshPublicHostKey) sshPublicHostKey); decltype(sshPublicHostKey)& sshPublicHostKey);
}; };
typedef std::vector<Machine> Machines; typedef std::vector<Machine> Machines;

View file

@ -171,8 +171,9 @@ void Store::queryMissing(const PathSet& targets, PathSet& willBuild_,
} }
}; };
auto checkOutput = [&](const Path& drvPath, ref<Derivation> drv, auto checkOutput = [&](const Path& drvPath, const ref<Derivation>& drv,
const Path& outPath, ref<Sync<DrvState>> drvState_) { const Path& outPath,
const ref<Sync<DrvState>>& drvState_) {
if (drvState_->lock()->done) { if (drvState_->lock()->done) {
return; return;
} }

View file

@ -94,7 +94,7 @@ struct NarAccessor : public FSAccessor {
} }
}; };
explicit NarAccessor(ref<const std::string> nar) : nar(nar) { explicit NarAccessor(const ref<const std::string>& nar) : nar(nar) {
NarIndexer indexer(*this, *nar); NarIndexer indexer(*this, *nar);
parseDump(indexer, indexer); parseDump(indexer, indexer);
} }
@ -111,7 +111,7 @@ struct NarAccessor : public FSAccessor {
if (type == "directory") { if (type == "directory") {
member.type = FSAccessor::Type::tDirectory; member.type = FSAccessor::Type::tDirectory;
for (auto i = v["entries"].begin(); i != v["entries"].end(); ++i) { for (auto i = v["entries"].begin(); i != v["entries"].end(); ++i) {
std::string name = i.key(); const std::string& name = i.key();
recurse(member.children[name], i.value()); recurse(member.children[name], i.value());
} }
} else if (type == "regular") { } else if (type == "regular") {
@ -225,8 +225,8 @@ ref<FSAccessor> makeLazyNarAccessor(const std::string& listing,
return make_ref<NarAccessor>(listing, getNarBytes); return make_ref<NarAccessor>(listing, getNarBytes);
} }
void listNar(JSONPlaceholder& res, ref<FSAccessor> accessor, const Path& path, void listNar(JSONPlaceholder& res, const ref<FSAccessor>& accessor,
bool recurse) { const Path& path, bool recurse) {
auto st = accessor->stat(path); auto st = accessor->stat(path);
auto obj = res.object(); auto obj = res.object();

View file

@ -23,7 +23,7 @@ class JSONPlaceholder;
/* Write a JSON representation of the contents of a NAR (except file /* Write a JSON representation of the contents of a NAR (except file
contents). */ contents). */
void listNar(JSONPlaceholder& res, ref<FSAccessor> accessor, const Path& path, void listNar(JSONPlaceholder& res, const ref<FSAccessor>& accessor,
bool recurse); const Path& path, bool recurse);
} // namespace nix } // namespace nix

View file

@ -122,7 +122,7 @@ std::string NarInfo::to_string() const {
res += "System: " + system + "\n"; res += "System: " + system + "\n";
} }
for (auto sig : sigs) { for (const auto& sig : sigs) {
res += "Sig: " + sig + "\n"; res += "Sig: " + sig + "\n";
} }

View file

@ -35,7 +35,7 @@ static int parseName(const string& profileName, const string& name) {
return -1; return -1;
} }
Generations findGenerations(Path profile, int& curGen) { Generations findGenerations(const Path& profile, int& curGen) {
Generations gens; Generations gens;
Path profileDir = dirOf(profile); Path profileDir = dirOf(profile);
@ -68,7 +68,8 @@ static void makeName(const Path& profile, unsigned int num, Path& outLink) {
outLink = prefix + "-link"; outLink = prefix + "-link";
} }
Path createGeneration(ref<LocalFSStore> store, Path profile, Path outPath) { Path createGeneration(const ref<LocalFSStore>& store, const Path& profile,
const Path& outPath) {
/* The new generation number should be higher than old the /* The new generation number should be higher than old the
previous ones. */ previous ones. */
int dummy; int dummy;
@ -226,7 +227,7 @@ void deleteGenerationsOlderThan(const Path& profile, const string& timeSpec,
deleteGenerationsOlderThan(profile, oldTime, dryRun); deleteGenerationsOlderThan(profile, oldTime, dryRun);
} }
void switchLink(Path link, Path target) { void switchLink(const Path& link, Path target) {
/* Hacky. */ /* Hacky. */
if (dirOf(target) == dirOf(link)) { if (dirOf(target) == dirOf(link)) {
target = baseNameOf(target); target = baseNameOf(target);

View file

@ -19,11 +19,12 @@ typedef list<Generation> Generations;
/* Returns the list of currently present generations for the specified /* Returns the list of currently present generations for the specified
profile, sorted by generation number. */ profile, sorted by generation number. */
Generations findGenerations(Path profile, int& curGen); Generations findGenerations(const Path& profile, int& curGen);
class LocalFSStore; class LocalFSStore;
Path createGeneration(ref<LocalFSStore> store, Path profile, Path outPath); Path createGeneration(const ref<LocalFSStore>& store, const Path& profile,
const Path& outPath);
void deleteGeneration(const Path& profile, unsigned int gen); void deleteGeneration(const Path& profile, unsigned int gen);
@ -40,7 +41,7 @@ void deleteGenerationsOlderThan(const Path& profile, time_t t, bool dryRun);
void deleteGenerationsOlderThan(const Path& profile, const string& timeSpec, void deleteGenerationsOlderThan(const Path& profile, const string& timeSpec,
bool dryRun); bool dryRun);
void switchLink(Path link, Path target); void switchLink(const Path& link, Path target);
/* Ensure exclusive access to a profile. Any command that modifies /* Ensure exclusive access to a profile. Any command that modifies
the profile first acquires this lock. */ the profile first acquires this lock. */

View file

@ -9,7 +9,8 @@
namespace nix { namespace nix {
RemoteFSAccessor::RemoteFSAccessor(ref<Store> store, const Path& cacheDir) RemoteFSAccessor::RemoteFSAccessor(const ref<Store>& store,
const Path& cacheDir)
: store(store), cacheDir(cacheDir) { : store(store), cacheDir(cacheDir) {
if (!cacheDir.empty()) { if (!cacheDir.empty()) {
createDirs(cacheDir); createDirs(cacheDir);
@ -23,7 +24,7 @@ Path RemoteFSAccessor::makeCacheFile(const Path& storePath,
} }
void RemoteFSAccessor::addToCache(const Path& storePath, const std::string& nar, void RemoteFSAccessor::addToCache(const Path& storePath, const std::string& nar,
ref<FSAccessor> narAccessor) { const ref<FSAccessor>& narAccessor) {
nars.emplace(storePath, narAccessor); nars.emplace(storePath, narAccessor);
if (!cacheDir.empty()) { if (!cacheDir.empty()) {

View file

@ -20,10 +20,10 @@ class RemoteFSAccessor : public FSAccessor {
Path makeCacheFile(const Path& storePath, const std::string& ext); Path makeCacheFile(const Path& storePath, const std::string& ext);
void addToCache(const Path& storePath, const std::string& nar, void addToCache(const Path& storePath, const std::string& nar,
ref<FSAccessor> narAccessor); const ref<FSAccessor>& narAccessor);
public: public:
RemoteFSAccessor(ref<Store> store, RemoteFSAccessor(const ref<Store>& store,
const /* FIXME: use std::optional */ Path& cacheDir = ""); const /* FIXME: use std::optional */ Path& cacheDir = "");
Stat stat(const Path& path) override; Stat stat(const Path& path) override;

View file

@ -1,6 +1,7 @@
#include "store-api.hh" #include "store-api.hh"
#include <future> #include <future>
#include <utility>
#include <glog/logging.h> #include <glog/logging.h>
@ -570,7 +571,7 @@ void Store::buildPaths(const PathSet& paths, BuildMode buildMode) {
} }
} }
void copyStorePath(ref<Store> srcStore, ref<Store> dstStore, void copyStorePath(ref<Store> srcStore, const ref<Store>& dstStore,
const Path& storePath, RepairFlag repair, const Path& storePath, RepairFlag repair,
CheckSigsFlag checkSigs) { CheckSigsFlag checkSigs) {
auto srcUri = srcStore->getUri(); auto srcUri = srcStore->getUri();
@ -693,7 +694,7 @@ void copyPaths(ref<Store> srcStore, ref<Store> dstStore,
}); });
} }
void copyClosure(ref<Store> srcStore, ref<Store> dstStore, void copyClosure(const ref<Store>& srcStore, const ref<Store>& dstStore,
const PathSet& storePaths, RepairFlag repair, const PathSet& storePaths, RepairFlag repair,
CheckSigsFlag checkSigs, SubstituteFlag substitute) { CheckSigsFlag checkSigs, SubstituteFlag substitute) {
PathSet closure; PathSet closure;
@ -824,14 +825,14 @@ void Store::addToStore(const ValidPathInfo& info, Source& narSource,
RepairFlag repair, CheckSigsFlag checkSigs, RepairFlag repair, CheckSigsFlag checkSigs,
std::shared_ptr<FSAccessor> accessor) { std::shared_ptr<FSAccessor> accessor) {
addToStore(info, make_ref<std::string>(narSource.drain()), repair, checkSigs, addToStore(info, make_ref<std::string>(narSource.drain()), repair, checkSigs,
accessor); std::move(accessor));
} }
void Store::addToStore(const ValidPathInfo& info, const ref<std::string>& nar, void Store::addToStore(const ValidPathInfo& info, const ref<std::string>& nar,
RepairFlag repair, CheckSigsFlag checkSigs, RepairFlag repair, CheckSigsFlag checkSigs,
std::shared_ptr<FSAccessor> accessor) { std::shared_ptr<FSAccessor> accessor) {
StringSource source(*nar); StringSource source(*nar);
addToStore(info, source, repair, checkSigs, accessor); addToStore(info, source, repair, checkSigs, std::move(accessor));
} }
} // namespace nix } // namespace nix
@ -851,7 +852,7 @@ std::pair<std::string, Store::Params> splitUriAndParams(
Store::Params params; Store::Params params;
auto q = uri.find('?'); auto q = uri.find('?');
if (q != std::string::npos) { if (q != std::string::npos) {
for (auto s : tokenizeString<Strings>(uri.substr(q + 1), "&")) { for (const auto& s : tokenizeString<Strings>(uri.substr(q + 1), "&")) {
auto e = s.find('='); auto e = s.find('=');
if (e != std::string::npos) { if (e != std::string::npos) {
auto value = s.substr(e + 1); auto value = s.substr(e + 1);
@ -885,7 +886,7 @@ ref<Store> openStore(const std::string& uri_,
auto params = extraParams; auto params = extraParams;
params.insert(uriParams.begin(), uriParams.end()); params.insert(uriParams.begin(), uriParams.end());
for (auto fun : *RegisterStoreImplementation::implementations) { for (const auto& fun : *RegisterStoreImplementation::implementations) {
auto store = fun(uri, params); auto store = fun(uri, params);
if (store) { if (store) {
store->warnUnknownSettings(); store->warnUnknownSettings();
@ -952,11 +953,11 @@ std::list<ref<Store>> getDefaultSubstituters() {
} }
}; };
for (auto uri : settings.substituters.get()) { for (const auto& uri : settings.substituters.get()) {
addStore(uri); addStore(uri);
} }
for (auto uri : settings.extraSubstituters.get()) { for (const auto& uri : settings.extraSubstituters.get()) {
addStore(uri); addStore(uri);
} }

View file

@ -564,7 +564,7 @@ class Store : public std::enable_shared_from_this<Store>, public Config {
the Nix store. Optionally, the contents of the NARs are the Nix store. Optionally, the contents of the NARs are
preloaded into the specified FS accessor to speed up subsequent preloaded into the specified FS accessor to speed up subsequent
access. */ access. */
Paths importPaths(Source& source, std::shared_ptr<FSAccessor> accessor, Paths importPaths(Source& source, const std::shared_ptr<FSAccessor>& accessor,
CheckSigsFlag checkSigs = CheckSigs); CheckSigsFlag checkSigs = CheckSigs);
struct Stats { struct Stats {
@ -671,7 +671,7 @@ string storePathToHash(const Path& path);
void checkStoreName(const string& name); void checkStoreName(const string& name);
/* Copy a path from one store to another. */ /* Copy a path from one store to another. */
void copyStorePath(ref<Store> srcStore, ref<Store> dstStore, void copyStorePath(ref<Store> srcStore, const ref<Store>& dstStore,
const Path& storePath, RepairFlag repair = NoRepair, const Path& storePath, RepairFlag repair = NoRepair,
CheckSigsFlag checkSigs = CheckSigs); CheckSigsFlag checkSigs = CheckSigs);
@ -686,7 +686,7 @@ void copyPaths(ref<Store> srcStore, ref<Store> dstStore,
SubstituteFlag substitute = NoSubstitute); SubstituteFlag substitute = NoSubstitute);
/* Copy the closure of the specified paths from one store to another. */ /* Copy the closure of the specified paths from one store to another. */
void copyClosure(ref<Store> srcStore, ref<Store> dstStore, void copyClosure(const ref<Store>& srcStore, const ref<Store>& dstStore,
const PathSet& storePaths, RepairFlag repair = NoRepair, const PathSet& storePaths, RepairFlag repair = NoRepair,
CheckSigsFlag checkSigs = CheckSigs, CheckSigsFlag checkSigs = CheckSigs,
SubstituteFlag substitute = NoSubstitute); SubstituteFlag substitute = NoSubstitute);

View file

@ -145,7 +145,7 @@ void dumpString(const std::string& s, Sink& sink) {
<< "contents" << s << ")"; << "contents" << s << ")";
} }
static SerialisationError badArchive(string s) { static SerialisationError badArchive(const string& s) {
return SerialisationError("bad archive: " + s); return SerialisationError("bad archive: " + s);
} }

View file

@ -175,7 +175,7 @@ Args::FlagMaker& Args::FlagMaker::mkHashTypeFlag(HashType* ht) {
arity(1); arity(1);
label("type"); label("type");
description("hash algorithm ('md5', 'sha1', 'sha256', or 'sha512')"); description("hash algorithm ('md5', 'sha1', 'sha256', or 'sha512')");
handler([ht](std::string s) { handler([ht](const std::string& s) {
*ht = parseHashType(s); *ht = parseHashType(s);
if (*ht == htUnknown) { if (*ht == htUnknown) {
throw UsageError("unknown hash type '%1%'", s); throw UsageError("unknown hash type '%1%'", s);

View file

@ -246,12 +246,12 @@ void BaseSetting<bool>::convertToArg(Args& args, const std::string& category) {
args.mkFlag() args.mkFlag()
.longName(name) .longName(name)
.description(description) .description(description)
.handler([=](std::vector<std::string> ss) { override(true); }) .handler([=](const std::vector<std::string>& ss) { override(true); })
.category(category); .category(category);
args.mkFlag() args.mkFlag()
.longName("no-" + name) .longName("no-" + name)
.description(description) .description(description)
.handler([=](std::vector<std::string> ss) { override(false); }) .handler([=](const std::vector<std::string>& ss) { override(false); })
.category(category); .category(category);
} }

View file

@ -157,8 +157,8 @@ size_t StringSource::read(unsigned char* data, size_t len) {
#error Coroutines are broken in this version of Boost! #error Coroutines are broken in this version of Boost!
#endif #endif
std::unique_ptr<Source> sinkToSource(std::function<void(Sink&)> fun, std::unique_ptr<Source> sinkToSource(const std::function<void(Sink&)>& fun,
std::function<void()> eof) { const std::function<void()>& eof) {
struct SinkToSource : Source { struct SinkToSource : Source {
using coro_t = boost::coroutines2::coroutine<std::string>; using coro_t = boost::coroutines2::coroutine<std::string>;

View file

@ -209,7 +209,8 @@ struct LambdaSource : Source {
/* Convert a function that feeds data into a Sink into a Source. The /* Convert a function that feeds data into a Sink into a Source. The
Source executes the function as a coroutine. */ Source executes the function as a coroutine. */
std::unique_ptr<Source> sinkToSource( std::unique_ptr<Source> sinkToSource(
std::function<void(Sink&)> fun, std::function<void()> eof = []() { const std::function<void(Sink&)>& fun,
const std::function<void()>& eof = []() {
throw EndOfFile("coroutine has finished"); throw EndOfFile("coroutine has finished");
}); });

View file

@ -76,9 +76,9 @@ void clearEnv() {
} }
} }
void replaceEnv(std::map<std::string, std::string> newEnv) { void replaceEnv(const std::map<std::string, std::string>& newEnv) {
clearEnv(); clearEnv();
for (auto newEnvVar : newEnv) { for (const auto& newEnvVar : newEnv) {
setenv(newEnvVar.first.c_str(), newEnvVar.second.c_str(), 1); setenv(newEnvVar.first.c_str(), newEnvVar.second.c_str(), 1);
} }
} }
@ -888,9 +888,9 @@ void killUser(uid_t uid) {
/* Wrapper around vfork to prevent the child process from clobbering /* Wrapper around vfork to prevent the child process from clobbering
the caller's stack frame in the parent. */ the caller's stack frame in the parent. */
static pid_t doFork(bool allowVfork, std::function<void()> fun) static pid_t doFork(bool allowVfork, const std::function<void()>& fun)
__attribute__((noinline)); __attribute__((noinline));
static pid_t doFork(bool allowVfork, std::function<void()> fun) { static pid_t doFork(bool allowVfork, const std::function<void()>& fun) {
#ifdef __linux__ #ifdef __linux__
pid_t pid = allowVfork ? vfork() : fork(); pid_t pid = allowVfork ? vfork() : fork();
#else #else
@ -944,7 +944,7 @@ std::vector<char*> stringsToCharPtrs(const Strings& ss) {
return res; return res;
} }
string runProgram(Path program, bool searchPath, const Strings& args, string runProgram(const Path& program, bool searchPath, const Strings& args,
const std::optional<std::string>& input) { const std::optional<std::string>& input) {
RunOptions opts(program, args); RunOptions opts(program, args);
opts.searchPath = searchPath; opts.searchPath = searchPath;
@ -1425,7 +1425,7 @@ string base64Decode(const string& s) {
} }
void callFailure(const std::function<void(std::exception_ptr exc)>& failure, void callFailure(const std::function<void(std::exception_ptr exc)>& failure,
std::exception_ptr exc) { const std::exception_ptr& exc) {
try { try {
failure(exc); failure(exc);
} catch (std::exception& e) { } catch (std::exception& e) {
@ -1516,7 +1516,7 @@ struct InterruptCallbackImpl : InterruptCallback {
}; };
std::unique_ptr<InterruptCallback> createInterruptCallback( std::unique_ptr<InterruptCallback> createInterruptCallback(
std::function<void()> callback) { const std::function<void()>& callback) {
auto interruptCallbacks(_interruptCallbacks.lock()); auto interruptCallbacks(_interruptCallbacks.lock());
interruptCallbacks->push_back(callback); interruptCallbacks->push_back(callback);

View file

@ -246,7 +246,7 @@ pid_t startProcess(std::function<void()> fun,
/* Run a program and return its stdout in a string (i.e., like the /* Run a program and return its stdout in a string (i.e., like the
shell backtick operator). */ shell backtick operator). */
string runProgram(Path program, bool searchPath = false, string runProgram(const Path& program, bool searchPath = false,
const Strings& args = Strings(), const Strings& args = Strings(),
const std::optional<std::string>& input = {}); const std::optional<std::string>& input = {});
@ -453,7 +453,7 @@ struct InterruptCallback {
/* Register a function that gets called on SIGINT (in a non-signal /* Register a function that gets called on SIGINT (in a non-signal
context). */ context). */
std::unique_ptr<InterruptCallback> createInterruptCallback( std::unique_ptr<InterruptCallback> createInterruptCallback(
std::function<void()> callback); const std::function<void()>& callback);
void triggerInterrupt(); void triggerInterrupt();

View file

@ -299,7 +299,7 @@ static void _main(int argc, char** argv) {
if (readStdin) { if (readStdin) {
exprs = {state->parseStdin()}; exprs = {state->parseStdin()};
} else { } else {
for (auto i : left) { for (const auto& i : left) {
if (fromArgs) { if (fromArgs) {
exprs.push_back(state->parseExprFromString(i, absPath("."))); exprs.push_back(state->parseExprFromString(i, absPath(".")));
} else { } else {

View file

@ -18,7 +18,7 @@ bool dryRun = false;
* Of course, this makes rollbacks to before this point in time * Of course, this makes rollbacks to before this point in time
* impossible. */ * impossible. */
void removeOldGenerations(std::string dir) { void removeOldGenerations(const std::string& dir) {
if (access(dir.c_str(), R_OK) != 0) { if (access(dir.c_str(), R_OK) != 0) {
return; return;
} }

View file

@ -194,9 +194,9 @@ struct RetrieveRegularNARSink : ParseSink {
} }
}; };
static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted, static void performOp(TunnelLogger* logger, const ref<Store>& store,
unsigned int clientVersion, Source& from, Sink& to, bool trusted, unsigned int clientVersion, Source& from,
unsigned int op) { Sink& to, unsigned int op) {
switch (op) { switch (op) {
case wopIsValidPath: { case wopIsValidPath: {
/* 'readStorePath' could raise an error leading to the connection /* 'readStorePath' could raise an error leading to the connection

View file

@ -171,8 +171,8 @@ static void loadSourceExpr(EvalState& state, const Path& path, Value& v) {
} }
} }
static void loadDerivations(EvalState& state, Path nixExprPath, static void loadDerivations(EvalState& state, const Path& nixExprPath,
string systemFilter, Bindings& autoArgs, const string& systemFilter, Bindings& autoArgs,
const string& pathPrefix, DrvInfos& elems) { const string& pathPrefix, DrvInfos& elems) {
Value vRoot; Value vRoot;
loadSourceExpr(state, nixExprPath, vRoot); loadSourceExpr(state, nixExprPath, vRoot);

View file

@ -79,7 +79,7 @@ void printClosure(const Path & nePath, const StoreExpr & fs)
} }
#endif #endif
void printDotGraph(ref<Store> store, const PathSet& roots) { void printDotGraph(const ref<Store>& store, const PathSet& roots) {
PathSet workList(roots); PathSet workList(roots);
PathSet doneSet; PathSet doneSet;

View file

@ -6,6 +6,6 @@ namespace nix {
class Store; class Store;
void printDotGraph(ref<Store> store, const PathSet& roots); void printDotGraph(const ref<Store>& store, const PathSet& roots);
} // namespace nix } // namespace nix

View file

@ -37,7 +37,7 @@ static string makeNode(const ValidPathInfo& info) {
(isDerivation(info.path) ? "derivation" : "output-path")); (isDerivation(info.path) ? "derivation" : "output-path"));
} }
void printGraphML(ref<Store> store, const PathSet& roots) { void printGraphML(const ref<Store>& store, const PathSet& roots) {
PathSet workList(roots); PathSet workList(roots);
PathSet doneSet; PathSet doneSet;
std::pair<PathSet::iterator, bool> ret; std::pair<PathSet::iterator, bool> ret;

View file

@ -6,6 +6,6 @@ namespace nix {
class Store; class Store;
void printGraphML(ref<Store> store, const PathSet& roots); void printGraphML(const ref<Store>& store, const PathSet& roots);
} // namespace nix } // namespace nix

View file

@ -28,6 +28,9 @@ using namespace nix;
using std::cin; using std::cin;
using std::cout; using std::cout;
// TODO(tazjin): clang-tidy's performance lints don't like this, but
// the automatic fixes fail (it seems that some of the ops want to own
// the args for whatever reason)
using Operation = void (*)(Strings, Strings); using Operation = void (*)(Strings, Strings);
static Path gcRoot; static Path gcRoot;

View file

@ -8,7 +8,7 @@ using namespace nix;
struct MixCat : virtual Args { struct MixCat : virtual Args {
std::string path; std::string path;
void cat(ref<FSAccessor> accessor) { void cat(const ref<FSAccessor>& accessor) {
auto st = accessor->stat(path); auto st = accessor->stat(path);
if (st.type == FSAccessor::Type::tMissing) { if (st.type == FSAccessor::Type::tMissing) {
throw Error(format("path '%1%' does not exist") % path); throw Error(format("path '%1%' does not exist") % path);

View file

@ -171,21 +171,23 @@ struct RegisterCommand {
}; };
std::shared_ptr<Installable> parseInstallable(SourceExprCommand& cmd, std::shared_ptr<Installable> parseInstallable(SourceExprCommand& cmd,
ref<Store> store, const ref<Store>& store,
const std::string& installable, const std::string& installable,
bool useDefaultInstallables); bool useDefaultInstallables);
Buildables build(ref<Store> store, RealiseMode mode, Buildables build(const ref<Store>& store, RealiseMode mode,
std::vector<std::shared_ptr<Installable>> installables); const std::vector<std::shared_ptr<Installable>>& installables);
PathSet toStorePaths(ref<Store> store, RealiseMode mode, PathSet toStorePaths(
std::vector<std::shared_ptr<Installable>> installables); const ref<Store>& store, RealiseMode mode,
const std::vector<std::shared_ptr<Installable>>& installables);
Path toStorePath(ref<Store> store, RealiseMode mode, Path toStorePath(const ref<Store>& store, RealiseMode mode,
std::shared_ptr<Installable> installable); const std::shared_ptr<Installable>& installable);
PathSet toDerivations(ref<Store> store, PathSet toDerivations(
std::vector<std::shared_ptr<Installable>> installables, const ref<Store>& store,
bool useDeriver = false); const std::vector<std::shared_ptr<Installable>>& installables,
bool useDeriver = false);
} // namespace nix } // namespace nix

View file

@ -64,7 +64,7 @@ struct CmdDoctor : StoreCommand {
return true; return true;
} }
static bool checkProfileRoots(ref<Store> store) { static bool checkProfileRoots(const ref<Store>& store) {
PathSet dirs; PathSet dirs;
for (auto& dir : tokenizeString<Strings>(getEnv("PATH"), ":")) { for (auto& dir : tokenizeString<Strings>(getEnv("PATH"), ":")) {

View file

@ -34,7 +34,7 @@ struct CmdHash : Command {
} }
void run() override { void run() override {
for (auto path : paths) { for (const auto& path : paths) {
Hash h = mode == mFile ? hashFile(ht, path) : hashPath(ht, path).first; Hash h = mode == mFile ? hashFile(ht, path) : hashPath(ht, path).first;
if (truncate && h.hashSize > 20) { if (truncate && h.hashSize > 20) {
h = compressHash(h, 20); h = compressHash(h, 20);
@ -73,7 +73,7 @@ struct CmdToBase : Command {
} }
void run() override { void run() override {
for (auto s : args) { for (const auto& s : args) {
std::cout << fmt("%s\n", Hash(s, ht).to_string(base, base == SRI)); std::cout << fmt("%s\n", Hash(s, ht).to_string(base, base == SRI));
} }
} }

View file

@ -198,8 +198,8 @@ std::string attrRegex = R"([A-Za-z_][A-Za-z0-9-_+]*)";
static std::regex attrPathRegex(fmt(R"(%1%(\.%1%)*)", attrRegex)); static std::regex attrPathRegex(fmt(R"(%1%(\.%1%)*)", attrRegex));
static std::vector<std::shared_ptr<Installable>> parseInstallables( static std::vector<std::shared_ptr<Installable>> parseInstallables(
SourceExprCommand& cmd, ref<Store> store, std::vector<std::string> ss, SourceExprCommand& cmd, const ref<Store>& store,
bool useDefaultInstallables) { std::vector<std::string> ss, bool useDefaultInstallables) {
std::vector<std::shared_ptr<Installable>> result; std::vector<std::shared_ptr<Installable>> result;
if (ss.empty() && useDefaultInstallables) { if (ss.empty() && useDefaultInstallables) {
@ -213,7 +213,7 @@ static std::vector<std::shared_ptr<Installable>> parseInstallables(
if (s.compare(0, 1, "(") == 0) { if (s.compare(0, 1, "(") == 0) {
result.push_back(std::make_shared<InstallableExpr>(cmd, s)); result.push_back(std::make_shared<InstallableExpr>(cmd, s));
} else if (s.find("/") != std::string::npos) { } else if (s.find('/') != std::string::npos) {
auto path = store->toStorePath(store->followLinksToStore(s)); auto path = store->toStorePath(store->followLinksToStore(s));
if (store->isStorePath(path)) { if (store->isStorePath(path)) {
@ -233,7 +233,7 @@ static std::vector<std::shared_ptr<Installable>> parseInstallables(
} }
std::shared_ptr<Installable> parseInstallable(SourceExprCommand& cmd, std::shared_ptr<Installable> parseInstallable(SourceExprCommand& cmd,
ref<Store> store, const ref<Store>& store,
const std::string& installable, const std::string& installable,
bool useDefaultInstallables) { bool useDefaultInstallables) {
auto installables = parseInstallables(cmd, store, {installable}, false); auto installables = parseInstallables(cmd, store, {installable}, false);
@ -241,8 +241,9 @@ std::shared_ptr<Installable> parseInstallable(SourceExprCommand& cmd,
return installables.front(); return installables.front();
} }
Buildables build(ref<Store> store, RealiseMode mode, Buildables build(
std::vector<std::shared_ptr<Installable>> installables) { const ref<Store>& store, RealiseMode mode,
const std::vector<std::shared_ptr<Installable>>& installables) {
if (mode != Build) { if (mode != Build) {
settings.readOnlyMode = true; settings.readOnlyMode = true;
} }
@ -278,8 +279,9 @@ Buildables build(ref<Store> store, RealiseMode mode,
return buildables; return buildables;
} }
PathSet toStorePaths(ref<Store> store, RealiseMode mode, PathSet toStorePaths(
std::vector<std::shared_ptr<Installable>> installables) { const ref<Store>& store, RealiseMode mode,
const std::vector<std::shared_ptr<Installable>>& installables) {
PathSet outPaths; PathSet outPaths;
for (auto& b : build(store, mode, installables)) { for (auto& b : build(store, mode, installables)) {
@ -291,8 +293,8 @@ PathSet toStorePaths(ref<Store> store, RealiseMode mode,
return outPaths; return outPaths;
} }
Path toStorePath(ref<Store> store, RealiseMode mode, Path toStorePath(const ref<Store>& store, RealiseMode mode,
std::shared_ptr<Installable> installable) { const std::shared_ptr<Installable>& installable) {
auto paths = toStorePaths(store, mode, {installable}); auto paths = toStorePaths(store, mode, {installable});
if (paths.size() != 1) { if (paths.size() != 1) {
@ -303,9 +305,10 @@ Path toStorePath(ref<Store> store, RealiseMode mode,
return *paths.begin(); return *paths.begin();
} }
PathSet toDerivations(ref<Store> store, PathSet toDerivations(
std::vector<std::shared_ptr<Installable>> installables, const ref<Store>& store,
bool useDeriver) { const std::vector<std::shared_ptr<Installable>>& installables,
bool useDeriver) {
PathSet drvPaths; PathSet drvPaths;
for (auto& i : installables) { for (auto& i : installables) {

View file

@ -74,7 +74,7 @@ struct MixLs : virtual Args, MixJSON {
showDirectory); showDirectory);
} }
void list(ref<FSAccessor> accessor) { void list(const ref<FSAccessor>& accessor) {
if (path == "/") { if (path == "/") {
path = ""; path = "";
} }

View file

@ -3,6 +3,7 @@
#include <cstdlib> #include <cstdlib>
#include <cstring> #include <cstring>
#include <iostream> #include <iostream>
#include <utility>
#include <glog/logging.h> #include <glog/logging.h>
@ -58,10 +59,10 @@ struct NixRepl {
const Path historyFile; const Path historyFile;
NixRepl(const Strings& searchPath, nix::ref<Store> store); NixRepl(const Strings& searchPath, const nix::ref<Store>& store);
~NixRepl(); ~NixRepl();
void mainLoop(const std::vector<std::string>& files); void mainLoop(const std::vector<std::string>& files);
StringSet completePrefix(string prefix); StringSet completePrefix(const string& prefix);
static 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);
@ -70,7 +71,7 @@ struct NixRepl {
void reloadFiles(); void reloadFiles();
void addAttrsToScope(Value& attrs); void addAttrsToScope(Value& attrs);
void addVarToScope(const Symbol& name, Value& v); void addVarToScope(const Symbol& name, Value& v);
Expr* parseString(string s); Expr* parseString(const string& s);
void evalString(string s, Value& v); void evalString(string s, Value& v);
using ValuesSeen = set<Value*>; using ValuesSeen = set<Value*>;
@ -129,7 +130,7 @@ string removeWhitespace(string s) {
return s; return s;
} }
NixRepl::NixRepl(const Strings& searchPath, nix::ref<Store> store) NixRepl::NixRepl(const Strings& searchPath, const nix::ref<Store>& store)
: state(searchPath, store), : state(searchPath, store),
staticEnv(false, &state.staticBaseEnv), staticEnv(false, &state.staticBaseEnv),
historyFile(getDataDir() + "/nix/repl-history") { historyFile(getDataDir() + "/nix/repl-history") {
@ -332,7 +333,7 @@ bool NixRepl::getLine(string& input, const std::string& prompt) {
return true; return true;
} }
StringSet NixRepl::completePrefix(string prefix) { StringSet NixRepl::completePrefix(const 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(){}[]");
@ -641,13 +642,13 @@ void NixRepl::addVarToScope(const Symbol& name, Value& v) {
varNames.insert((string)name); varNames.insert((string)name);
} }
Expr* NixRepl::parseString(string s) { Expr* NixRepl::parseString(const string& s) {
Expr* e = state.parseExprFromString(s, curDir, staticEnv); Expr* e = state.parseExprFromString(s, curDir, staticEnv);
return e; return e;
} }
void NixRepl::evalString(string s, Value& v) { void NixRepl::evalString(string s, Value& v) {
Expr* e = parseString(s); Expr* e = parseString(std::move(s));
e->eval(state, *env, v); e->eval(state, *env, v);
state.forceValue(v); state.forceValue(v);
} }

View file

@ -30,7 +30,7 @@ struct CmdRun : InstallablesCommand {
.description("command and arguments to be executed; defaults to 'bash'") .description("command and arguments to be executed; defaults to 'bash'")
.labels({"command", "args"}) .labels({"command", "args"})
.arity(ArityAny) .arity(ArityAny)
.handler([&](std::vector<std::string> ss) { .handler([&](const std::vector<std::string>& ss) {
if (ss.empty()) { if (ss.empty()) {
throw UsageError("--command requires at least one argument"); throw UsageError("--command requires at least one argument");
} }
@ -227,7 +227,7 @@ void chrootHelper(int argc, char** argv) {
throw SysError("mounting '%s' on '%s'", realStoreDir, storeDir); throw SysError("mounting '%s' on '%s'", realStoreDir, storeDir);
} }
for (auto entry : readDirectory("/")) { for (const auto& entry : readDirectory("/")) {
auto src = "/" + entry.name; auto src = "/" + entry.name;
auto st = lstat(src); auto st = lstat(src);
if (!S_ISDIR(st.st_mode)) { if (!S_ISDIR(st.st_mode)) {

View file

@ -16,12 +16,12 @@
using namespace nix; using namespace nix;
std::string wrap(std::string prefix, std::string s) { std::string wrap(const std::string& prefix, const std::string& s) {
return prefix + s + ANSI_NORMAL; return prefix + s + ANSI_NORMAL;
} }
std::string hilite(const std::string& s, const std::smatch& m, std::string hilite(const std::string& s, const std::smatch& m,
std::string postfix) { const std::string& postfix) {
return m.empty() ? s return m.empty() ? s
: std::string(m.prefix()) + ANSI_RED + std::string(m.str()) + : std::string(m.prefix()) + ANSI_RED + std::string(m.str()) +
postfix + std::string(m.suffix()); postfix + std::string(m.suffix());
@ -99,7 +99,7 @@ struct CmdSearch : SourceExprCommand, MixJSON {
std::function<void(Value*, std::string, bool, JSONObject*)> doExpr; std::function<void(Value*, std::string, bool, JSONObject*)> doExpr;
doExpr = [&](Value* v, std::string attrPath, bool toplevel, doExpr = [&](Value* v, const std::string& attrPath, bool toplevel,
JSONObject* cache) { JSONObject* cache) {
DLOG(INFO) << "at attribute '" << attrPath << "'"; DLOG(INFO) << "at attribute '" << attrPath << "'";
@ -262,7 +262,7 @@ struct CmdSearch : SourceExprCommand, MixJSON {
} }
RunPager pager; RunPager pager;
for (auto el : results) { for (const auto& el : results) {
std::cout << el.second << "\n"; std::cout << el.second << "\n";
} }
} }

View file

@ -97,7 +97,7 @@ struct CmdUpgradeNix : MixDryRun, StoreCommand {
} }
/* Return the profile in which Nix is installed. */ /* Return the profile in which Nix is installed. */
static Path getProfileDir(ref<Store> store) { static Path getProfileDir(const ref<Store>& store) {
Path where; Path where;
for (auto& dir : tokenizeString<Strings>(getEnv("PATH"), ":")) { for (auto& dir : tokenizeString<Strings>(getEnv("PATH"), ":")) {
@ -143,7 +143,7 @@ struct CmdUpgradeNix : MixDryRun, StoreCommand {
} }
/* Return the store path of the latest stable Nix. */ /* Return the store path of the latest stable Nix. */
Path getLatestNix(ref<Store> store) { Path getLatestNix(const ref<Store>& store) {
// FIXME: use nixos.org? // FIXME: use nixos.org?
auto req = DownloadRequest(storePathsUrl); auto req = DownloadRequest(storePathsUrl);
auto res = getDownloader()->download(req); auto res = getDownloader()->download(req);

View file

@ -102,8 +102,8 @@ struct CmdVerify : StorePathsCommand {
size_t actualSigsNeeded = std::max(sigsNeeded, (size_t)1); size_t actualSigsNeeded = std::max(sigsNeeded, (size_t)1);
size_t validSigs = 0; size_t validSigs = 0;
auto doSigs = [&](StringSet sigs) { auto doSigs = [&](const StringSet& sigs) {
for (auto sig : sigs) { for (const auto& sig : sigs) {
if (sigsSeen.count(sig) != 0u) { if (sigsSeen.count(sig) != 0u) {
continue; continue;
} }