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 "
"names")
.label("path")
.handler([&](std::string s) { searchPath.push_back(s); });
.handler([&](const std::string& s) { searchPath.push_back(s); });
}
Bindings* MixEvalArgs::getAutoArgs(EvalState& state) {

View file

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

View file

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

View file

@ -15,7 +15,7 @@ namespace nix {
DrvInfo::DrvInfo(EvalState& state, string attrPath, Bindings* attrs)
: 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)
: state(&state), attrPath("") {
auto spec = parseDrvPathWithOutputs(drvPathWithOutputs);

View file

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

View file

@ -34,7 +34,7 @@ namespace nix {
name>. */
std::pair<string, string> decodeContext(const string& s) {
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),
string(s, 1, index - 1));
}
@ -2172,7 +2172,7 @@ static void prim_splitVersion(EvalState& state, const Pos& pos, Value** args,
unsigned int n = 0;
for (auto& component : components) {
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::RegisterPrimOp(std::string name, size_t arity, PrimOpFun fun) {
RegisterPrimOp::RegisterPrimOp(const std::string& name, size_t arity,
PrimOpFun fun) {
if (primOps == nullptr) {
primOps = new PrimOps;
}

View file

@ -11,7 +11,7 @@ struct RegisterPrimOp {
/* You can register a constant by passing an arity of 0. fun
will get called during EvalState initialization, so there
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

View file

@ -26,7 +26,7 @@ MixCommonArgs::MixCommonArgs(const string& programName)
.shortName('j')
.label("jobs")
.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";
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 narSize;
PathSet willBuild;
@ -48,7 +48,7 @@ void printMissing(ref<Store> store, const PathSet& paths) {
narSize);
}
void printMissing(ref<Store> store, const PathSet& willBuild,
void printMissing(const ref<Store>& store, const PathSet& willBuild,
const PathSet& willSubstitute, const PathSet& unknown,
unsigned long long downloadSize, unsigned long long narSize) {
if (!willBuild.empty()) {
@ -260,14 +260,15 @@ void parseCmdLine(
int argc, char** argv,
std::function<bool(Strings::iterator& arg, const Strings::iterator& end)>
parseArg) {
parseCmdLine(baseNameOf(argv[0]), argvToStrings(argc, argv), parseArg);
parseCmdLine(baseNameOf(argv[0]), argvToStrings(argc, argv),
std::move(parseArg));
}
void parseCmdLine(
const string& programName, const Strings& args,
std::function<bool(Strings::iterator& arg, const Strings::iterator& end)>
parseArg) {
LegacyArgs(programName, parseArg).parseCmdline(args);
LegacyArgs(programName, std::move(parseArg)).parseCmdline(args);
}
void printVersion(const string& programName) {
@ -298,7 +299,8 @@ void showManPage(const string& name) {
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
string error = ANSI_RED "error:" ANSI_NORMAL " ";

View file

@ -18,7 +18,8 @@ class Exit : public std::exception {
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! */
void initNix();
@ -40,9 +41,9 @@ void printGCWarning();
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,
unsigned long long downloadSize, unsigned long long narSize);

View file

@ -98,7 +98,7 @@ Path BinaryCacheStore::narInfoFileFor(const Path& storePath) {
return storePathToHash(storePath) + ".narinfo";
}
void BinaryCacheStore::writeNarInfo(ref<NarInfo> narInfo) {
void BinaryCacheStore::writeNarInfo(const ref<NarInfo>& narInfo) {
auto narInfoFile = narInfoFileFor(narInfo->path);
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);
void writeNarInfo(ref<NarInfo> narInfo);
void writeNarInfo(const ref<NarInfo>& narInfo);
public:
bool isValidPathUncached(const Path& path) override;

View file

@ -145,7 +145,7 @@ class Goal : public std::enable_shared_from_this<Goal> {
public:
virtual void work() = 0;
void addWaitee(GoalPtr waitee);
void addWaitee(const GoalPtr& waitee);
virtual void waiteeDone(GoalPtr waitee, ExitCode result);
@ -280,10 +280,10 @@ class Worker {
RepairFlag repair = NoRepair);
/* 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). */
void wakeUp(GoalPtr goal);
void wakeUp(const GoalPtr& goal);
/* Return the number of local build and substitution processes
currently running (but not remote builds via the build
@ -292,7 +292,7 @@ class Worker {
/* Registers a running child process. `inBuildSlot' means that
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);
/* 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
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 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: O(n)
for (auto& i : goals) {
@ -343,7 +343,7 @@ void addToWeakGoals(WeakGoals& goals, GoalPtr p) {
goals.push_back(p);
}
void Goal::addWaitee(GoalPtr waitee) {
void Goal::addWaitee(const GoalPtr& waitee) {
waitees.insert(waitee);
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;
if (diffHook != "" && settings.runDiffHook) {
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.uid = uid;
diffHookOptions.gid = gid;
@ -979,7 +981,7 @@ class DerivationGoal : public Goal {
void done(BuildResult::Status status, const string& msg = "");
PathSet exportReferences(PathSet storePaths);
PathSet exportReferences(const PathSet& storePaths);
};
const Path DerivationGoal::homeDir = "/homeless-shelter";
@ -1520,7 +1522,7 @@ void DerivationGoal::tryToBuild() {
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
tmpPath (the replacement), so we have to move it out of the
way first. We'd better not be interrupted here, because if
@ -1840,7 +1842,7 @@ int childEntry(void* arg) {
return 1;
}
PathSet DerivationGoal::exportReferences(PathSet storePaths) {
PathSet DerivationGoal::exportReferences(const PathSet& storePaths) {
PathSet paths;
for (auto storePath : storePaths) {
@ -4455,7 +4457,7 @@ GoalPtr Worker::makeSubstitutionGoal(const Path& path, RepairFlag repair) {
return goal;
}
static void removeGoal(GoalPtr goal, WeakGoalMap& goalMap) {
static void removeGoal(const GoalPtr& goal, WeakGoalMap& goalMap) {
/* !!! inefficient */
for (auto i = goalMap.begin(); i != goalMap.end();) {
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, substitutionGoals);
if (topGoals.find(goal) != topGoals.end()) {
@ -4492,15 +4494,15 @@ void Worker::removeGoal(GoalPtr goal) {
waitingForAnyGoal.clear();
}
void Worker::wakeUp(GoalPtr goal) {
void Worker::wakeUp(const GoalPtr& goal) {
goal->trace("woken up");
addToWeakGoals(awake, goal);
}
unsigned Worker::getNrLocalBuilds() { return nrLocalBuilds; }
void Worker::childStarted(GoalPtr goal, const set<int>& fds, bool inBuildSlot,
bool respectTimeouts) {
void Worker::childStarted(const GoalPtr& goal, const set<int>& fds,
bool inBuildSlot, bool respectTimeouts) {
Child child;
child.goal = goal;
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";
if (getNrLocalBuilds() < settings.maxBuildJobs) {
wakeUp(goal); /* we can do it right away */
@ -4553,12 +4555,12 @@ void Worker::waitForBuildSlot(GoalPtr goal) {
void Worker::waitForAnyGoal(GoalPtr goal) {
DLOG(INFO) << "wait for any goal";
addToWeakGoals(waitingForAnyGoal, goal);
addToWeakGoals(waitingForAnyGoal, std::move(goal));
}
void Worker::waitForAWhile(GoalPtr goal) {
DLOG(INFO) << "wait for a while";
addToWeakGoals(waitingForAWhile, goal);
addToWeakGoals(waitingForAWhile, std::move(goal));
}
void Worker::run(const Goals& _topGoals) {

View file

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

View file

@ -38,7 +38,7 @@ bool BasicDerivation::isBuiltin() const {
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) {
PathSet references;
references.insert(drv.inputSrcs.begin(), drv.inputSrcs.end());
@ -355,7 +355,7 @@ Hash hashDerivationModulo(Store& store, Derivation drv) {
}
DrvPathWithOutputs parseDrvPathWithOutputs(const string& s) {
size_t n = s.find("!");
size_t n = s.find('!');
return n == std::string::npos
? DrvPathWithOutputs(s, std::set<string>())
: DrvPathWithOutputs(

View file

@ -67,7 +67,7 @@ struct Derivation : BasicDerivation {
class Store;
/* 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);
/* 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);
done = true;
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://") &&
!hasPrefix(item->request.uri, "https://")) {
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(
ref<Store> store, const CachedDownloadRequest& request) {
const ref<Store>& store, const CachedDownloadRequest& request) {
auto url = resolveUri(request.uri);
auto name = request.name;

View file

@ -108,7 +108,7 @@ struct Downloader {
and is more recent than tarball-ttl seconds. Otherwise,
use the recorded ETag to verify if the server has a more
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);
enum Error { NotFound, Forbidden, Misc, Transient, Interrupted };

View file

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

View file

@ -149,17 +149,18 @@ void BaseSetting<SandboxMode>::convertToArg(Args& args,
args.mkFlag()
.longName(name)
.description("Enable sandboxing.")
.handler([=](std::vector<std::string> ss) { override(smEnabled); })
.handler([=](const std::vector<std::string>& ss) { override(smEnabled); })
.category(category);
args.mkFlag()
.longName("no-" + name)
.description("Disable sandboxing.")
.handler([=](std::vector<std::string> ss) { override(smDisabled); })
.handler(
[=](const std::vector<std::string>& ss) { override(smDisabled); })
.category(category);
args.mkFlag()
.longName("relaxed-" + name)
.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);
}

View file

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

View file

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

View file

@ -19,12 +19,12 @@ struct Machine {
bool mandatoryMet(const std::set<string>& features) const;
Machine(decltype(storeUri) storeUri, decltype(systemTypes) systemTypes,
decltype(sshKey) sshKey, decltype(maxJobs) maxJobs,
Machine(decltype(storeUri)& storeUri, decltype(systemTypes)& systemTypes,
decltype(sshKey)& sshKey, decltype(maxJobs) maxJobs,
decltype(speedFactor) speedFactor,
decltype(supportedFeatures) supportedFeatures,
decltype(mandatoryFeatures) mandatoryFeatures,
decltype(sshPublicHostKey) sshPublicHostKey);
decltype(supportedFeatures)& supportedFeatures,
decltype(mandatoryFeatures)& mandatoryFeatures,
decltype(sshPublicHostKey)& sshPublicHostKey);
};
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,
const Path& outPath, ref<Sync<DrvState>> drvState_) {
auto checkOutput = [&](const Path& drvPath, const ref<Derivation>& drv,
const Path& outPath,
const ref<Sync<DrvState>>& drvState_) {
if (drvState_->lock()->done) {
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);
parseDump(indexer, indexer);
}
@ -111,7 +111,7 @@ struct NarAccessor : public FSAccessor {
if (type == "directory") {
member.type = FSAccessor::Type::tDirectory;
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());
}
} else if (type == "regular") {
@ -225,8 +225,8 @@ ref<FSAccessor> makeLazyNarAccessor(const std::string& listing,
return make_ref<NarAccessor>(listing, getNarBytes);
}
void listNar(JSONPlaceholder& res, ref<FSAccessor> accessor, const Path& path,
bool recurse) {
void listNar(JSONPlaceholder& res, const ref<FSAccessor>& accessor,
const Path& path, bool recurse) {
auto st = accessor->stat(path);
auto obj = res.object();

View file

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

View file

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

View file

@ -35,7 +35,7 @@ static int parseName(const string& profileName, const string& name) {
return -1;
}
Generations findGenerations(Path profile, int& curGen) {
Generations findGenerations(const Path& profile, int& curGen) {
Generations gens;
Path profileDir = dirOf(profile);
@ -68,7 +68,8 @@ static void makeName(const Path& profile, unsigned int num, Path& outLink) {
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
previous ones. */
int dummy;
@ -226,7 +227,7 @@ void deleteGenerationsOlderThan(const Path& profile, const string& timeSpec,
deleteGenerationsOlderThan(profile, oldTime, dryRun);
}
void switchLink(Path link, Path target) {
void switchLink(const Path& link, Path target) {
/* Hacky. */
if (dirOf(target) == dirOf(link)) {
target = baseNameOf(target);

View file

@ -19,11 +19,12 @@ typedef list<Generation> Generations;
/* Returns the list of currently present generations for the specified
profile, sorted by generation number. */
Generations findGenerations(Path profile, int& curGen);
Generations findGenerations(const Path& profile, int& curGen);
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);
@ -40,7 +41,7 @@ void deleteGenerationsOlderThan(const Path& profile, time_t t, bool dryRun);
void deleteGenerationsOlderThan(const Path& profile, const string& timeSpec,
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
the profile first acquires this lock. */

View file

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

View file

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

View file

@ -1,6 +1,7 @@
#include "store-api.hh"
#include <future>
#include <utility>
#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,
CheckSigsFlag checkSigs) {
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,
CheckSigsFlag checkSigs, SubstituteFlag substitute) {
PathSet closure;
@ -824,14 +825,14 @@ void Store::addToStore(const ValidPathInfo& info, Source& narSource,
RepairFlag repair, CheckSigsFlag checkSigs,
std::shared_ptr<FSAccessor> accessor) {
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,
RepairFlag repair, CheckSigsFlag checkSigs,
std::shared_ptr<FSAccessor> accessor) {
StringSource source(*nar);
addToStore(info, source, repair, checkSigs, accessor);
addToStore(info, source, repair, checkSigs, std::move(accessor));
}
} // namespace nix
@ -851,7 +852,7 @@ std::pair<std::string, Store::Params> splitUriAndParams(
Store::Params params;
auto q = uri.find('?');
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('=');
if (e != std::string::npos) {
auto value = s.substr(e + 1);
@ -885,7 +886,7 @@ ref<Store> openStore(const std::string& uri_,
auto params = extraParams;
params.insert(uriParams.begin(), uriParams.end());
for (auto fun : *RegisterStoreImplementation::implementations) {
for (const auto& fun : *RegisterStoreImplementation::implementations) {
auto store = fun(uri, params);
if (store) {
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);
}
for (auto uri : settings.extraSubstituters.get()) {
for (const auto& uri : settings.extraSubstituters.get()) {
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
preloaded into the specified FS accessor to speed up subsequent
access. */
Paths importPaths(Source& source, std::shared_ptr<FSAccessor> accessor,
Paths importPaths(Source& source, const std::shared_ptr<FSAccessor>& accessor,
CheckSigsFlag checkSigs = CheckSigs);
struct Stats {
@ -671,7 +671,7 @@ string storePathToHash(const Path& path);
void checkStoreName(const string& name);
/* 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,
CheckSigsFlag checkSigs = CheckSigs);
@ -686,7 +686,7 @@ void copyPaths(ref<Store> srcStore, ref<Store> dstStore,
SubstituteFlag substitute = NoSubstitute);
/* 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,
CheckSigsFlag checkSigs = CheckSigs,
SubstituteFlag substitute = NoSubstitute);

View file

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

View file

@ -175,7 +175,7 @@ Args::FlagMaker& Args::FlagMaker::mkHashTypeFlag(HashType* ht) {
arity(1);
label("type");
description("hash algorithm ('md5', 'sha1', 'sha256', or 'sha512')");
handler([ht](std::string s) {
handler([ht](const std::string& s) {
*ht = parseHashType(s);
if (*ht == htUnknown) {
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()
.longName(name)
.description(description)
.handler([=](std::vector<std::string> ss) { override(true); })
.handler([=](const std::vector<std::string>& ss) { override(true); })
.category(category);
args.mkFlag()
.longName("no-" + name)
.description(description)
.handler([=](std::vector<std::string> ss) { override(false); })
.handler([=](const std::vector<std::string>& ss) { override(false); })
.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!
#endif
std::unique_ptr<Source> sinkToSource(std::function<void(Sink&)> fun,
std::function<void()> eof) {
std::unique_ptr<Source> sinkToSource(const std::function<void(Sink&)>& fun,
const std::function<void()>& eof) {
struct SinkToSource : Source {
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
Source executes the function as a coroutine. */
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");
});

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();
for (auto newEnvVar : newEnv) {
for (const auto& newEnvVar : newEnv) {
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
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));
static pid_t doFork(bool allowVfork, std::function<void()> fun) {
static pid_t doFork(bool allowVfork, const std::function<void()>& fun) {
#ifdef __linux__
pid_t pid = allowVfork ? vfork() : fork();
#else
@ -944,7 +944,7 @@ std::vector<char*> stringsToCharPtrs(const Strings& ss) {
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) {
RunOptions opts(program, args);
opts.searchPath = searchPath;
@ -1425,7 +1425,7 @@ string base64Decode(const string& s) {
}
void callFailure(const std::function<void(std::exception_ptr exc)>& failure,
std::exception_ptr exc) {
const std::exception_ptr& exc) {
try {
failure(exc);
} catch (std::exception& e) {
@ -1516,7 +1516,7 @@ struct InterruptCallbackImpl : InterruptCallback {
};
std::unique_ptr<InterruptCallback> createInterruptCallback(
std::function<void()> callback) {
const std::function<void()>& callback) {
auto interruptCallbacks(_interruptCallbacks.lock());
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
shell backtick operator). */
string runProgram(Path program, bool searchPath = false,
string runProgram(const Path& program, bool searchPath = false,
const Strings& args = Strings(),
const std::optional<std::string>& input = {});
@ -453,7 +453,7 @@ struct InterruptCallback {
/* Register a function that gets called on SIGINT (in a non-signal
context). */
std::unique_ptr<InterruptCallback> createInterruptCallback(
std::function<void()> callback);
const std::function<void()>& callback);
void triggerInterrupt();

View file

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

View file

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

View file

@ -194,9 +194,9 @@ struct RetrieveRegularNARSink : ParseSink {
}
};
static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
unsigned int clientVersion, Source& from, Sink& to,
unsigned int op) {
static void performOp(TunnelLogger* logger, const ref<Store>& store,
bool trusted, unsigned int clientVersion, Source& from,
Sink& to, unsigned int op) {
switch (op) {
case wopIsValidPath: {
/* '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,
string systemFilter, Bindings& autoArgs,
static void loadDerivations(EvalState& state, const Path& nixExprPath,
const string& systemFilter, Bindings& autoArgs,
const string& pathPrefix, DrvInfos& elems) {
Value vRoot;
loadSourceExpr(state, nixExprPath, vRoot);

View file

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

View file

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

View file

@ -37,7 +37,7 @@ static string makeNode(const ValidPathInfo& info) {
(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 doneSet;
std::pair<PathSet::iterator, bool> ret;

View file

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

View file

@ -28,6 +28,9 @@ using namespace nix;
using std::cin;
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);
static Path gcRoot;

View file

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

View file

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

View file

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

View file

@ -34,7 +34,7 @@ struct CmdHash : Command {
}
void run() override {
for (auto path : paths) {
for (const auto& path : paths) {
Hash h = mode == mFile ? hashFile(ht, path) : hashPath(ht, path).first;
if (truncate && h.hashSize > 20) {
h = compressHash(h, 20);
@ -73,7 +73,7 @@ struct CmdToBase : Command {
}
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));
}
}

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::vector<std::shared_ptr<Installable>> parseInstallables(
SourceExprCommand& cmd, ref<Store> store, std::vector<std::string> ss,
bool useDefaultInstallables) {
SourceExprCommand& cmd, const ref<Store>& store,
std::vector<std::string> ss, bool useDefaultInstallables) {
std::vector<std::shared_ptr<Installable>> result;
if (ss.empty() && useDefaultInstallables) {
@ -213,7 +213,7 @@ static std::vector<std::shared_ptr<Installable>> parseInstallables(
if (s.compare(0, 1, "(") == 0) {
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));
if (store->isStorePath(path)) {
@ -233,7 +233,7 @@ static std::vector<std::shared_ptr<Installable>> parseInstallables(
}
std::shared_ptr<Installable> parseInstallable(SourceExprCommand& cmd,
ref<Store> store,
const ref<Store>& store,
const std::string& installable,
bool useDefaultInstallables) {
auto installables = parseInstallables(cmd, store, {installable}, false);
@ -241,8 +241,9 @@ std::shared_ptr<Installable> parseInstallable(SourceExprCommand& cmd,
return installables.front();
}
Buildables build(ref<Store> store, RealiseMode mode,
std::vector<std::shared_ptr<Installable>> installables) {
Buildables build(
const ref<Store>& store, RealiseMode mode,
const std::vector<std::shared_ptr<Installable>>& installables) {
if (mode != Build) {
settings.readOnlyMode = true;
}
@ -278,8 +279,9 @@ Buildables build(ref<Store> store, RealiseMode mode,
return buildables;
}
PathSet toStorePaths(ref<Store> store, RealiseMode mode,
std::vector<std::shared_ptr<Installable>> installables) {
PathSet toStorePaths(
const ref<Store>& store, RealiseMode mode,
const std::vector<std::shared_ptr<Installable>>& installables) {
PathSet outPaths;
for (auto& b : build(store, mode, installables)) {
@ -291,8 +293,8 @@ PathSet toStorePaths(ref<Store> store, RealiseMode mode,
return outPaths;
}
Path toStorePath(ref<Store> store, RealiseMode mode,
std::shared_ptr<Installable> installable) {
Path toStorePath(const ref<Store>& store, RealiseMode mode,
const std::shared_ptr<Installable>& installable) {
auto paths = toStorePaths(store, mode, {installable});
if (paths.size() != 1) {
@ -303,9 +305,10 @@ Path toStorePath(ref<Store> store, RealiseMode mode,
return *paths.begin();
}
PathSet toDerivations(ref<Store> store,
std::vector<std::shared_ptr<Installable>> installables,
bool useDeriver) {
PathSet toDerivations(
const ref<Store>& store,
const std::vector<std::shared_ptr<Installable>>& installables,
bool useDeriver) {
PathSet drvPaths;
for (auto& i : installables) {

View file

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

View file

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

View file

@ -30,7 +30,7 @@ struct CmdRun : InstallablesCommand {
.description("command and arguments to be executed; defaults to 'bash'")
.labels({"command", "args"})
.arity(ArityAny)
.handler([&](std::vector<std::string> ss) {
.handler([&](const std::vector<std::string>& ss) {
if (ss.empty()) {
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);
}
for (auto entry : readDirectory("/")) {
for (const auto& entry : readDirectory("/")) {
auto src = "/" + entry.name;
auto st = lstat(src);
if (!S_ISDIR(st.st_mode)) {

View file

@ -16,12 +16,12 @@
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;
}
std::string hilite(const std::string& s, const std::smatch& m,
std::string postfix) {
const std::string& postfix) {
return m.empty() ? s
: std::string(m.prefix()) + ANSI_RED + std::string(m.str()) +
postfix + std::string(m.suffix());
@ -99,7 +99,7 @@ struct CmdSearch : SourceExprCommand, MixJSON {
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) {
DLOG(INFO) << "at attribute '" << attrPath << "'";
@ -262,7 +262,7 @@ struct CmdSearch : SourceExprCommand, MixJSON {
}
RunPager pager;
for (auto el : results) {
for (const auto& el : results) {
std::cout << el.second << "\n";
}
}

View file

@ -97,7 +97,7 @@ struct CmdUpgradeNix : MixDryRun, StoreCommand {
}
/* Return the profile in which Nix is installed. */
static Path getProfileDir(ref<Store> store) {
static Path getProfileDir(const ref<Store>& store) {
Path where;
for (auto& dir : tokenizeString<Strings>(getEnv("PATH"), ":")) {
@ -143,7 +143,7 @@ struct CmdUpgradeNix : MixDryRun, StoreCommand {
}
/* Return the store path of the latest stable Nix. */
Path getLatestNix(ref<Store> store) {
Path getLatestNix(const ref<Store>& store) {
// FIXME: use nixos.org?
auto req = DownloadRequest(storePathsUrl);
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 validSigs = 0;
auto doSigs = [&](StringSet sigs) {
for (auto sig : sigs) {
auto doSigs = [&](const StringSet& sigs) {
for (const auto& sig : sigs) {
if (sigsSeen.count(sig) != 0u) {
continue;
}