treewide: rename nix::fmt to nix::boostfmt

This was mostly automated with clangd, but a couple dozen stragglers or
so that weren't caught by clangd were done by hand.

Change-Id: I1d9551690d4b36cd9ff92517184586c341bad92a
This commit is contained in:
Qyriad 2024-07-04 09:38:59 -06:00
parent d31a814266
commit 4347f4ef70
88 changed files with 322 additions and 322 deletions

View file

@ -48,7 +48,7 @@ static std::string makeLockFilename(const std::string & storeUri) {
static AutoCloseFD openSlotLock(const Machine & m, uint64_t slot) static AutoCloseFD openSlotLock(const Machine & m, uint64_t slot)
{ {
return openLockFile(fmt("%s/%s-%d", currentLoad, makeLockFilename(m.storeUri), slot), true); return openLockFile(boostfmt("%s/%s-%d", currentLoad, makeLockFilename(m.storeUri), slot), true);
} }
static bool allSupportedLocally(Store & store, const std::set<std::string>& requiredFeatures) { static bool allSupportedLocally(Store & store, const std::set<std::string>& requiredFeatures) {
@ -245,7 +245,7 @@ static int main_build_remote(int argc, char * * argv)
try { try {
Activity act(*logger, lvlTalkative, actUnknown, fmt("connecting to '%s'", bestMachine->storeUri)); Activity act(*logger, lvlTalkative, actUnknown, boostfmt("connecting to '%s'", bestMachine->storeUri));
sshStore = bestMachine->openStore(); sshStore = bestMachine->openStore();
sshStore->connect(); sshStore->connect();
@ -279,7 +279,7 @@ connected:
AutoCloseFD uploadLock = openLockFile(lockFileName, true); AutoCloseFD uploadLock = openLockFile(lockFileName, true);
{ {
Activity act(*logger, lvlTalkative, actUnknown, fmt("waiting for the upload lock to '%s'", storeUri)); Activity act(*logger, lvlTalkative, actUnknown, boostfmt("waiting for the upload lock to '%s'", storeUri));
auto old = signal(SIGALRM, handleAlarm); auto old = signal(SIGALRM, handleAlarm);
alarm(15 * 60); alarm(15 * 60);
@ -292,7 +292,7 @@ connected:
auto substitute = settings.buildersUseSubstitutes ? Substitute : NoSubstitute; auto substitute = settings.buildersUseSubstitutes ? Substitute : NoSubstitute;
{ {
Activity act(*logger, lvlTalkative, actUnknown, fmt("copying dependencies to '%s'", storeUri)); Activity act(*logger, lvlTalkative, actUnknown, boostfmt("copying dependencies to '%s'", storeUri));
copyPaths(*store, *sshStore, store->parseStorePathSet(inputs), NoRepair, NoCheckSigs, substitute); copyPaths(*store, *sshStore, store->parseStorePathSet(inputs), NoRepair, NoCheckSigs, substitute);
} }
@ -373,7 +373,7 @@ connected:
} }
if (!missingPaths.empty()) { if (!missingPaths.empty()) {
Activity act(*logger, lvlTalkative, actUnknown, fmt("copying outputs from '%s'", storeUri)); Activity act(*logger, lvlTalkative, actUnknown, boostfmt("copying outputs from '%s'", storeUri));
if (auto localStore = store.dynamic_pointer_cast<LocalStore>()) if (auto localStore = store.dynamic_pointer_cast<LocalStore>())
for (auto & path : missingPaths) for (auto & path : missingPaths)
localStore->locksHeld.insert(store->printStorePath(path)); /* FIXME: ugly */ localStore->locksHeld.insert(store->printStorePath(path)); /* FIXME: ugly */

View file

@ -43,7 +43,7 @@ bool ProfileElementSource::operator<(const ProfileElementSource & other) const
std::string ProfileElementSource::to_string() const std::string ProfileElementSource::to_string() const
{ {
return fmt("%s#%s%s", originalRef, attrPath, outputs.to_string()); return boostfmt("%s#%s%s", originalRef, attrPath, outputs.to_string());
} }
std::string ProfileElement::identifier() const std::string ProfileElement::identifier() const

View file

@ -305,7 +305,7 @@ void MixEnvironment::setEnviron() {
for (const auto & var : keep) { for (const auto & var : keep) {
auto val = getenv(var.c_str()); auto val = getenv(var.c_str());
if (val) stringsEnv.emplace_back(fmt("%s=%s", var.c_str(), val)); if (val) stringsEnv.emplace_back(boostfmt("%s=%s", var.c_str(), val));
} }
vectorEnv = stringsToCharPtrs(stringsEnv); vectorEnv = stringsToCharPtrs(stringsEnv);

View file

@ -16,7 +16,7 @@ Strings editorFor(const SourcePath & file, uint32_t line)
editor.find("nano") != std::string::npos || editor.find("nano") != std::string::npos ||
editor.find("vim") != std::string::npos || editor.find("vim") != std::string::npos ||
editor.find("kak") != std::string::npos)) editor.find("kak") != std::string::npos))
args.push_back(fmt("+%d", line)); args.push_back(boostfmt("+%d", line));
args.push_back(path->abs()); args.push_back(path->abs());
return args; return args;
} }

View file

@ -50,7 +50,7 @@ DerivedPathsWithInfo InstallableAttrPath::toDerivedPaths()
if (std::optional derivedPathWithInfo = trySinglePathToDerivedPaths( if (std::optional derivedPathWithInfo = trySinglePathToDerivedPaths(
*v, *v,
pos, pos,
fmt("while evaluating the attribute '%s'", attrPath))) boostfmt("while evaluating the attribute '%s'", attrPath)))
{ {
return { *derivedPathWithInfo }; return { *derivedPathWithInfo };
} }

View file

@ -87,7 +87,7 @@ InstallableFlake::InstallableFlake(
DerivedPathsWithInfo InstallableFlake::toDerivedPaths() DerivedPathsWithInfo InstallableFlake::toDerivedPaths()
{ {
Activity act(*logger, lvlTalkative, actUnknown, fmt("evaluating derivation '%s'", what())); Activity act(*logger, lvlTalkative, actUnknown, boostfmt("evaluating derivation '%s'", what()));
auto attr = getCursor(*state); auto attr = getCursor(*state);
@ -101,7 +101,7 @@ DerivedPathsWithInfo InstallableFlake::toDerivedPaths()
if (std::optional derivedPathWithInfo = trySinglePathToDerivedPaths( if (std::optional derivedPathWithInfo = trySinglePathToDerivedPaths(
v, v,
noPos, noPos,
fmt("while evaluating the flake output attribute '%s'", attrPath))) boostfmt("while evaluating the flake output attribute '%s'", attrPath)))
{ {
return { *derivedPathWithInfo }; return { *derivedPathWithInfo };
} else { } else {

View file

@ -158,9 +158,9 @@ std::string showType(const Value & v)
switch (v.internalType) { switch (v.internalType) {
case tString: return v.string.context ? "a string with context" : "a string"; case tString: return v.string.context ? "a string with context" : "a string";
case tPrimOp: case tPrimOp:
return fmt("the built-in function '%s'", std::string(v.primOp->name)); return boostfmt("the built-in function '%s'", std::string(v.primOp->name));
case tPrimOpApp: case tPrimOpApp:
return fmt("the partially applied built-in function '%s'", std::string(getPrimOp(v)->primOp->name)); return boostfmt("the partially applied built-in function '%s'", std::string(getPrimOp(v)->primOp->name));
case tExternal: return v.external->showType(); case tExternal: return v.external->showType();
case tThunk: return v.isBlackhole() ? "a black hole" : "a thunk"; case tThunk: return v.isBlackhole() ? "a black hole" : "a thunk";
case tApp: return "a function application"; case tApp: return "a function application";

View file

@ -43,7 +43,7 @@ void ConfigFile::apply()
if (auto* s = std::get_if<std::string>(&value)) if (auto* s = std::get_if<std::string>(&value))
valueS = *s; valueS = *s;
else if (auto* n = std::get_if<int64_t>(&value)) else if (auto* n = std::get_if<int64_t>(&value))
valueS = fmt("%d", *n); valueS = boostfmt("%d", *n);
else if (auto* b = std::get_if<Explicit<bool>>(&value)) else if (auto* b = std::get_if<Explicit<bool>>(&value))
valueS = b->t ? "true" : "false"; valueS = b->t ? "true" : "false";
else if (auto ss = std::get_if<std::vector<std::string>>(&value)) else if (auto ss = std::get_if<std::vector<std::string>>(&value))
@ -66,12 +66,12 @@ void ConfigFile::apply()
printInfo("Using saved setting for '%s = %s' from ~/.local/share/nix/trusted-settings.json.", name, valueS); printInfo("Using saved setting for '%s = %s' from ~/.local/share/nix/trusted-settings.json.", name, valueS);
} else { } else {
// FIXME: filter ANSI escapes, newlines, \r, etc. // FIXME: filter ANSI escapes, newlines, \r, etc.
if (std::tolower(logger->ask(fmt("Do you want to allow configuration setting '%s' to be set to '" ANSI_RED "%s" ANSI_NORMAL "' (y/N)? This may allow the flake to gain root, see the nix.conf manual page.", name, valueS)).value_or('n')) == 'y') { if (std::tolower(logger->ask(boostfmt("Do you want to allow configuration setting '%s' to be set to '" ANSI_RED "%s" ANSI_NORMAL "' (y/N)? This may allow the flake to gain root, see the nix.conf manual page.", name, valueS)).value_or('n')) == 'y') {
trusted = true; trusted = true;
} else { } else {
warn("you can set '%s' to '%b' to automatically reject configuration options supplied by flakes", "accept-flake-config", false); warn("you can set '%s' to '%b' to automatically reject configuration options supplied by flakes", "accept-flake-config", false);
} }
if (std::tolower(logger->ask(fmt("do you want to permanently mark this value as %s (y/N)?", trusted ? "trusted": "untrusted" )).value_or('n')) == 'y') { if (std::tolower(logger->ask(boostfmt("do you want to permanently mark this value as %s (y/N)?", trusted ? "trusted": "untrusted" )).value_or('n')) == 'y') {
trustedList[name][valueS] = trusted; trustedList[name][valueS] = trusted;
writeTrustedList(trustedList); writeTrustedList(trustedList);
} }

View file

@ -664,7 +664,7 @@ LockedFlake lockFlake(
if (!lockFlags.updateLockFile) if (!lockFlags.updateLockFile)
throw Error("flake '%s' requires lock file changes but they're not allowed due to '--no-update-lock-file'", topRef); throw Error("flake '%s' requires lock file changes but they're not allowed due to '--no-update-lock-file'", topRef);
auto newLockFileS = fmt("%s\n", newLockFile); auto newLockFileS = boostfmt("%s\n", newLockFile);
if (lockFlags.outputLockFilePath) { if (lockFlags.outputLockFilePath) {
if (lockFlags.commitLockFile) if (lockFlags.commitLockFile)
@ -693,7 +693,7 @@ LockedFlake lockFlake(
cm = fetchSettings.commitLockFileSummary.get(); cm = fetchSettings.commitLockFileSummary.get();
if (cm == "") { if (cm == "") {
cm = fmt("%s: %s", relPath, lockFileExists ? "Update" : "Add"); cm = boostfmt("%s: %s", relPath, lockFileExists ? "Update" : "Add");
} }
cm += "\n\nFlake lock file updates:\n\n"; cm += "\n\nFlake lock file updates:\n\n";
@ -925,7 +925,7 @@ Fingerprint LockedFlake::getFingerprint() const
// and we haven't changed it, then it's sufficient to use // and we haven't changed it, then it's sufficient to use
// flake.sourceInfo.storePath for the fingerprint. // flake.sourceInfo.storePath for the fingerprint.
return hashString(htSHA256, return hashString(htSHA256,
fmt("%s;%s;%d;%d;%s", boostfmt("%s;%s;%d;%d;%s",
flake.sourceInfo->storePath.to_string(), flake.sourceInfo->storePath.to_string(),
flake.lockedRef.subdir, flake.lockedRef.subdir,
flake.lockedRef.input.getRevCount().value_or(0), flake.lockedRef.input.getRevCount().value_or(0),

View file

@ -132,7 +132,7 @@ nlohmann::json LockFile::toJSON() const
if (!keys.insert(key).second) { if (!keys.insert(key).second) {
for (int n = 2; ; ++n) { for (int n = 2; ; ++n) {
auto k = fmt("%s_%d", key, n); auto k = boostfmt("%s_%d", key, n);
if (keys.insert(k).second) { if (keys.insert(k).second) {
key = k; key = k;
break; break;
@ -199,7 +199,7 @@ std::ostream & operator <<(std::ostream & stream, const LockFile & lockFile)
void LockFile::write(const Path & path) const void LockFile::write(const Path & path) const
{ {
createDirs(dirOf(path)); createDirs(dirOf(path));
writeFile(path, fmt("%s\n", *this)); writeFile(path, boostfmt("%s\n", *this));
} }
std::optional<FlakeRef> LockFile::isUnlocked() const std::optional<FlakeRef> LockFile::isUnlocked() const
@ -279,10 +279,10 @@ std::map<InputPath, Node::Edge> LockFile::getAllInputs() const
static std::string describe(const FlakeRef & flakeRef) static std::string describe(const FlakeRef & flakeRef)
{ {
auto s = fmt("'%s'", flakeRef.to_string()); auto s = boostfmt("'%s'", flakeRef.to_string());
if (auto lastModified = flakeRef.input.getLastModified()) if (auto lastModified = flakeRef.input.getLastModified())
s += fmt(" (%s)", std::put_time(std::gmtime(&*lastModified), "%Y-%m-%d")); s += boostfmt(" (%s)", std::put_time(std::gmtime(&*lastModified), "%Y-%m-%d"));
return s; return s;
} }
@ -292,7 +292,7 @@ std::ostream & operator <<(std::ostream & stream, const Node::Edge & edge)
if (auto node = std::get_if<0>(&edge)) if (auto node = std::get_if<0>(&edge))
stream << describe((*node)->lockedRef); stream << describe((*node)->lockedRef);
else if (auto follows = std::get_if<1>(&edge)) else if (auto follows = std::get_if<1>(&edge))
stream << fmt("follows '%s'", printInputPath(*follows)); stream << boostfmt("follows '%s'", printInputPath(*follows));
return stream; return stream;
} }
@ -318,15 +318,15 @@ std::string LockFile::diff(const LockFile & oldLocks, const LockFile & newLocks)
while (i != oldFlat.end() || j != newFlat.end()) { while (i != oldFlat.end() || j != newFlat.end()) {
if (j != newFlat.end() && (i == oldFlat.end() || i->first > j->first)) { if (j != newFlat.end() && (i == oldFlat.end() || i->first > j->first)) {
res += fmt("" ANSI_GREEN "Added input '%s':" ANSI_NORMAL "\n %s\n", res += boostfmt("" ANSI_GREEN "Added input '%s':" ANSI_NORMAL "\n %s\n",
printInputPath(j->first), j->second); printInputPath(j->first), j->second);
++j; ++j;
} else if (i != oldFlat.end() && (j == newFlat.end() || i->first < j->first)) { } else if (i != oldFlat.end() && (j == newFlat.end() || i->first < j->first)) {
res += fmt("" ANSI_RED "Removed input '%s'" ANSI_NORMAL "\n", printInputPath(i->first)); res += boostfmt("" ANSI_RED "Removed input '%s'" ANSI_NORMAL "\n", printInputPath(i->first));
++i; ++i;
} else { } else {
if (!equals(i->second, j->second)) { if (!equals(i->second, j->second)) {
res += fmt("" ANSI_BOLD "Updated input '%s':" ANSI_NORMAL "\n %s\n → %s\n", res += boostfmt("" ANSI_BOLD "Updated input '%s':" ANSI_NORMAL "\n %s\n → %s\n",
printInputPath(i->first), printInputPath(i->first),
i->second, i->second,
j->second); j->second);

View file

@ -392,7 +392,7 @@ static void getDerivations(EvalState & state, Value & vIn,
// NOTE we can't really deduplicate here because small lists don't have stable addresses // NOTE we can't really deduplicate here because small lists don't have stable addresses
// and can cause spurious duplicate detections due to v being on the stack. // and can cause spurious duplicate detections due to v being on the stack.
for (auto [n, elem] : enumerate(v.listItems())) { for (auto [n, elem] : enumerate(v.listItems())) {
std::string pathPrefix2 = addToPath(pathPrefix, fmt("%d", n)); std::string pathPrefix2 = addToPath(pathPrefix, boostfmt("%d", n));
if (getDerivation(state, *elem, pathPrefix2, drvs, ignoreAssertionFailures)) if (getDerivation(state, *elem, pathPrefix2, drvs, ignoreAssertionFailures))
getDerivations(state, *elem, pathPrefix2, autoArgs, drvs, done, ignoreAssertionFailures); getDerivations(state, *elem, pathPrefix2, autoArgs, drvs, done, ignoreAssertionFailures);
} }

View file

@ -577,7 +577,7 @@ std::string ExprLambda::showNamePos(const EvalState & state) const
std::string id(name std::string id(name
? concatStrings("'", state.symbols[name], "'") ? concatStrings("'", state.symbols[name], "'")
: "anonymous function"); : "anonymous function");
return fmt("%1% at %2%", id, state.positions[pos]); return boostfmt("%1% at %2%", id, state.positions[pos]);
} }

View file

@ -81,7 +81,7 @@ struct Control : p::must_if<SyntaxErrors>::control<Rule>
if (in.empty()) { if (in.empty()) {
std::string expected; std::string expected;
if constexpr (constexpr auto msg = error_message<Rule>) if constexpr (constexpr auto msg = error_message<Rule>)
expected = fmt(", %s", msg); expected = boostfmt(", %s", msg);
throw p::parse_error("unexpected end of file" + expected, in); throw p::parse_error("unexpected end of file" + expected, in);
} }
p::must_if<SyntaxErrors>::control<Rule>::raise(in, st...); p::must_if<SyntaxErrors>::control<Rule>::raise(in, st...);

View file

@ -65,7 +65,7 @@ void emitTreeAttrs(
if (auto lastModified = input.getLastModified()) { if (auto lastModified = input.getLastModified()) {
attrs.alloc("lastModified").mkInt(*lastModified); attrs.alloc("lastModified").mkInt(*lastModified);
attrs.alloc("lastModifiedDate").mkString( attrs.alloc("lastModifiedDate").mkString(
fmt("%s", std::put_time(std::gmtime(&*lastModified), "%Y%m%d%H%M%S"))); boostfmt("%s", std::put_time(std::gmtime(&*lastModified), "%Y%m%d%H%M%S")));
} }
v.mkAttrs(attrs); v.mkAttrs(attrs);

View file

@ -23,8 +23,8 @@ static void posToXML(EvalState & state, XMLAttrs & xmlAttrs, const Pos & pos)
{ {
if (auto path = std::get_if<SourcePath>(&pos.origin)) if (auto path = std::get_if<SourcePath>(&pos.origin))
xmlAttrs["path"] = path->path.abs(); xmlAttrs["path"] = path->path.abs();
xmlAttrs["line"] = fmt("%1%", pos.line); xmlAttrs["line"] = boostfmt("%1%", pos.line);
xmlAttrs["column"] = fmt("%1%", pos.column); xmlAttrs["column"] = boostfmt("%1%", pos.column);
} }
@ -61,7 +61,7 @@ static void printValueAsXML(EvalState & state, bool strict, bool location,
switch (v.type()) { switch (v.type()) {
case nInt: case nInt:
doc.writeEmptyElement("int", singletonAttrs("value", fmt("%1%", v.integer))); doc.writeEmptyElement("int", singletonAttrs("value", boostfmt("%1%", v.integer)));
break; break;
case nBool: case nBool:
@ -153,7 +153,7 @@ static void printValueAsXML(EvalState & state, bool strict, bool location,
break; break;
case nFloat: case nFloat:
doc.writeEmptyElement("float", singletonAttrs("value", fmt("%1%", v.fpoint))); doc.writeEmptyElement("float", singletonAttrs("value", boostfmt("%1%", v.fpoint)));
break; break;
case nThunk: case nThunk:

View file

@ -94,7 +94,7 @@ std::map<std::string, std::string> attrsToQuery(const Attrs & attrs)
std::map<std::string, std::string> query; std::map<std::string, std::string> query;
for (auto & attr : attrs) { for (auto & attr : attrs) {
if (auto v = std::get_if<uint64_t>(&attr.second)) { if (auto v = std::get_if<uint64_t>(&attr.second)) {
query.insert_or_assign(attr.first, fmt("%d", *v)); query.insert_or_assign(attr.first, boostfmt("%d", *v));
} else if (auto v = std::get_if<std::string>(&attr.second)) { } else if (auto v = std::get_if<std::string>(&attr.second)) {
query.insert_or_assign(attr.first, *v); query.insert_or_assign(attr.first, *v);
} else if (auto v = std::get_if<Explicit<bool>>(&attr.second)) { } else if (auto v = std::get_if<Explicit<bool>>(&attr.second)) {

View file

@ -12,7 +12,7 @@ StorePath fetchToStore(
PathFilter * filter, PathFilter * filter,
RepairFlag repair) RepairFlag repair)
{ {
Activity act(*logger, lvlChatty, actUnknown, fmt("copying '%s' to the store", path)); Activity act(*logger, lvlChatty, actUnknown, boostfmt("copying '%s' to the store", path));
auto filter2 = filter ? *filter : defaultPathFilter; auto filter2 = filter ? *filter : defaultPathFilter;

View file

@ -576,7 +576,7 @@ struct GitInputScheme : InputScheme
} }
if (doFetch) { if (doFetch) {
Activity act(*logger, lvlTalkative, actUnknown, fmt("fetching Git repository '%s'", actualUrl)); Activity act(*logger, lvlTalkative, actUnknown, boostfmt("fetching Git repository '%s'", actualUrl));
// FIXME: git stderr messes up our progress indicator, so // FIXME: git stderr messes up our progress indicator, so
// we're using --quiet for now. Should process its stderr. // we're using --quiet for now. Should process its stderr.
@ -589,7 +589,7 @@ struct GitInputScheme : InputScheme
: ref == "HEAD" : ref == "HEAD"
? *ref ? *ref
: "refs/heads/" + *ref; : "refs/heads/" + *ref;
runProgram("git", true, { "-C", repoDir, "--git-dir", gitDir, "fetch", "--quiet", "--force", "--", actualUrl, fmt("%s:%s", fetchRef, fetchRef) }, true); runProgram("git", true, { "-C", repoDir, "--git-dir", gitDir, "fetch", "--quiet", "--force", "--", actualUrl, boostfmt("%s:%s", fetchRef, fetchRef) }, true);
} catch (Error & e) { } catch (Error & e) {
if (!pathExists(localRefFile)) throw; if (!pathExists(localRefFile)) throw;
warn("could not update local clone of Git repository '%s'; continuing with the most recent version", actualUrl); warn("could not update local clone of Git repository '%s'; continuing with the most recent version", actualUrl);
@ -654,7 +654,7 @@ struct GitInputScheme : InputScheme
// TODO: repoDir might lack the ref (it only checks if rev // TODO: repoDir might lack the ref (it only checks if rev
// exists, see FIXME above) so use a big hammer and fetch // exists, see FIXME above) so use a big hammer and fetch
// everything to ensure we get the rev. // everything to ensure we get the rev.
Activity act(*logger, lvlTalkative, actUnknown, fmt("making temporary clone of '%s'", repoDir)); Activity act(*logger, lvlTalkative, actUnknown, boostfmt("making temporary clone of '%s'", repoDir));
runProgram("git", true, { "-C", tmpDir, "fetch", "--quiet", "--force", runProgram("git", true, { "-C", tmpDir, "fetch", "--quiet", "--force",
"--update-head-ok", "--", repoDir, "refs/*:refs/*" }, true); "--update-head-ok", "--", repoDir, "refs/*:refs/*" }, true);
} }
@ -677,12 +677,12 @@ struct GitInputScheme : InputScheme
source repo if it exists. */ source repo if it exists. */
auto modulesPath = repoDir + "/" + gitDir + "/modules"; auto modulesPath = repoDir + "/" + gitDir + "/modules";
if (pathExists(modulesPath)) { if (pathExists(modulesPath)) {
Activity act(*logger, lvlTalkative, actUnknown, fmt("copying submodules of '%s'", actualUrl)); Activity act(*logger, lvlTalkative, actUnknown, boostfmt("copying submodules of '%s'", actualUrl));
runProgram("cp", true, { "-R", "--", modulesPath, tmpGitDir + "/modules" }); runProgram("cp", true, { "-R", "--", modulesPath, tmpGitDir + "/modules" });
} }
{ {
Activity act(*logger, lvlTalkative, actUnknown, fmt("fetching submodules of '%s'", actualUrl)); Activity act(*logger, lvlTalkative, actUnknown, boostfmt("fetching submodules of '%s'", actualUrl));
runProgram("git", true, { "-C", tmpDir, "submodule", "--quiet", "update", "--init", "--recursive" }, true); runProgram("git", true, { "-C", tmpDir, "submodule", "--quiet", "update", "--init", "--recursive" }, true);
} }

View file

@ -217,7 +217,7 @@ struct GitHubInputScheme : GitArchiveInputScheme
// is used here. See // is used here. See
// https://developer.github.com/v3/#authentication and // https://developer.github.com/v3/#authentication and
// https://docs.github.com/en/developers/apps/authorizing-oath-apps // https://docs.github.com/en/developers/apps/authorizing-oath-apps
return std::pair<std::string, std::string>("Authorization", fmt("token %s", token)); return std::pair<std::string, std::string>("Authorization", boostfmt("token %s", token));
} }
std::string getHost(const Input & input) const std::string getHost(const Input & input) const
@ -238,7 +238,7 @@ struct GitHubInputScheme : GitArchiveInputScheme
Hash getRevFromRef(nix::ref<Store> store, const Input & input) const override Hash getRevFromRef(nix::ref<Store> store, const Input & input) const override
{ {
auto host = getHost(input); auto host = getHost(input);
auto url = fmt( auto url = boostfmt(
host == "github.com" host == "github.com"
? "https://api.%s/repos/%s/%s/commits/%s" ? "https://api.%s/repos/%s/%s/commits/%s"
: "https://%s/api/v3/repos/%s/%s/commits/%s", : "https://%s/api/v3/repos/%s/%s/commits/%s",
@ -270,7 +270,7 @@ struct GitHubInputScheme : GitArchiveInputScheme
? "https://%s/%s/%s/archive/%s.tar.gz" ? "https://%s/%s/%s/archive/%s.tar.gz"
: "https://api.%s/repos/%s/%s/tarball/%s"; : "https://api.%s/repos/%s/%s/tarball/%s";
const auto url = fmt(urlFmt, host, getOwner(input), getRepo(input), const auto url = boostfmt(urlFmt, host, getOwner(input), getRepo(input),
input.getRev()->to_string(Base16, false)); input.getRev()->to_string(Base16, false));
return DownloadUrl { url, headers }; return DownloadUrl { url, headers };
@ -279,7 +279,7 @@ struct GitHubInputScheme : GitArchiveInputScheme
void clone(const Input & input, const Path & destDir) const override void clone(const Input & input, const Path & destDir) const override
{ {
auto host = getHost(input); auto host = getHost(input);
Input::fromURL(fmt("git+https://%s/%s/%s.git", Input::fromURL(boostfmt("git+https://%s/%s/%s.git",
host, getOwner(input), getRepo(input))) host, getOwner(input), getRepo(input)))
.applyOverrides(input.getRef(), input.getRev()) .applyOverrides(input.getRef(), input.getRev())
.clone(destDir); .clone(destDir);
@ -302,7 +302,7 @@ struct GitLabInputScheme : GitArchiveInputScheme
auto fldsplit = token.find_first_of(':'); auto fldsplit = token.find_first_of(':');
// n.b. C++20 would allow: if (token.starts_with("OAuth2:")) ... // n.b. C++20 would allow: if (token.starts_with("OAuth2:")) ...
if ("OAuth2" == token.substr(0, fldsplit)) if ("OAuth2" == token.substr(0, fldsplit))
return std::make_pair("Authorization", fmt("Bearer %s", token.substr(fldsplit+1))); return std::make_pair("Authorization", boostfmt("Bearer %s", token.substr(fldsplit+1)));
if ("PAT" == token.substr(0, fldsplit)) if ("PAT" == token.substr(0, fldsplit))
return std::make_pair("Private-token", token.substr(fldsplit+1)); return std::make_pair("Private-token", token.substr(fldsplit+1));
warn("Unrecognized GitLab token type %s", token.substr(0, fldsplit)); warn("Unrecognized GitLab token type %s", token.substr(0, fldsplit));
@ -313,7 +313,7 @@ struct GitLabInputScheme : GitArchiveInputScheme
{ {
auto host = maybeGetStrAttr(input.attrs, "host").value_or("gitlab.com"); auto host = maybeGetStrAttr(input.attrs, "host").value_or("gitlab.com");
// See rate limiting note below // See rate limiting note below
auto url = fmt("https://%s/api/v4/projects/%s%%2F%s/repository/commits?ref_name=%s", auto url = boostfmt("https://%s/api/v4/projects/%s%%2F%s/repository/commits?ref_name=%s",
host, getStrAttr(input.attrs, "owner"), getStrAttr(input.attrs, "repo"), *input.getRef()); host, getStrAttr(input.attrs, "owner"), getStrAttr(input.attrs, "repo"), *input.getRef());
Headers headers = makeHeadersWithAuthTokens(host); Headers headers = makeHeadersWithAuthTokens(host);
@ -341,7 +341,7 @@ struct GitLabInputScheme : GitArchiveInputScheme
// is 10 reqs/sec/ip-addr. See // is 10 reqs/sec/ip-addr. See
// https://docs.gitlab.com/ee/user/gitlab_com/index.html#gitlabcom-specific-rate-limits // https://docs.gitlab.com/ee/user/gitlab_com/index.html#gitlabcom-specific-rate-limits
auto host = maybeGetStrAttr(input.attrs, "host").value_or("gitlab.com"); auto host = maybeGetStrAttr(input.attrs, "host").value_or("gitlab.com");
auto url = fmt("https://%s/api/v4/projects/%s%%2F%s/repository/archive.tar.gz?sha=%s", auto url = boostfmt("https://%s/api/v4/projects/%s%%2F%s/repository/archive.tar.gz?sha=%s",
host, getStrAttr(input.attrs, "owner"), getStrAttr(input.attrs, "repo"), host, getStrAttr(input.attrs, "owner"), getStrAttr(input.attrs, "repo"),
input.getRev()->to_string(Base16, false)); input.getRev()->to_string(Base16, false));
@ -353,7 +353,7 @@ struct GitLabInputScheme : GitArchiveInputScheme
{ {
auto host = maybeGetStrAttr(input.attrs, "host").value_or("gitlab.com"); auto host = maybeGetStrAttr(input.attrs, "host").value_or("gitlab.com");
// FIXME: get username somewhere // FIXME: get username somewhere
Input::fromURL(fmt("git+https://%s/%s/%s.git", Input::fromURL(boostfmt("git+https://%s/%s/%s.git",
host, getStrAttr(input.attrs, "owner"), getStrAttr(input.attrs, "repo"))) host, getStrAttr(input.attrs, "owner"), getStrAttr(input.attrs, "repo")))
.applyOverrides(input.getRef(), input.getRev()) .applyOverrides(input.getRef(), input.getRev())
.clone(destDir); .clone(destDir);
@ -368,7 +368,7 @@ struct SourceHutInputScheme : GitArchiveInputScheme
{ {
// SourceHut supports both PAT and OAuth2. See // SourceHut supports both PAT and OAuth2. See
// https://man.sr.ht/meta.sr.ht/oauth.md // https://man.sr.ht/meta.sr.ht/oauth.md
return std::pair<std::string, std::string>("Authorization", fmt("Bearer %s", token)); return std::pair<std::string, std::string>("Authorization", boostfmt("Bearer %s", token));
// Note: This currently serves no purpose, as this kind of authorization // Note: This currently serves no purpose, as this kind of authorization
// does not allow for downloading tarballs on sourcehut private repos. // does not allow for downloading tarballs on sourcehut private repos.
// Once it is implemented, however, should work as expected. // Once it is implemented, however, should work as expected.
@ -382,7 +382,7 @@ struct SourceHutInputScheme : GitArchiveInputScheme
auto ref = *input.getRef(); auto ref = *input.getRef();
auto host = maybeGetStrAttr(input.attrs, "host").value_or("git.sr.ht"); auto host = maybeGetStrAttr(input.attrs, "host").value_or("git.sr.ht");
auto base_url = fmt("https://%s/%s/%s", auto base_url = boostfmt("https://%s/%s/%s",
host, getStrAttr(input.attrs, "owner"), getStrAttr(input.attrs, "repo")); host, getStrAttr(input.attrs, "owner"), getStrAttr(input.attrs, "repo"));
Headers headers = makeHeadersWithAuthTokens(host); Headers headers = makeHeadersWithAuthTokens(host);
@ -390,7 +390,7 @@ struct SourceHutInputScheme : GitArchiveInputScheme
std::string refUri; std::string refUri;
if (ref == "HEAD") { if (ref == "HEAD") {
auto file = store->toRealPath( auto file = store->toRealPath(
downloadFile(store, fmt("%s/HEAD", base_url), "source", false, headers).storePath); downloadFile(store, boostfmt("%s/HEAD", base_url), "source", false, headers).storePath);
std::ifstream is(file); std::ifstream is(file);
std::string line; std::string line;
getline(is, line); getline(is, line);
@ -401,12 +401,12 @@ struct SourceHutInputScheme : GitArchiveInputScheme
} }
refUri = remoteLine->target; refUri = remoteLine->target;
} else { } else {
refUri = fmt("refs/(heads|tags)/%s", ref); refUri = boostfmt("refs/(heads|tags)/%s", ref);
} }
std::regex refRegex(refUri); std::regex refRegex(refUri);
auto file = store->toRealPath( auto file = store->toRealPath(
downloadFile(store, fmt("%s/info/refs", base_url), "source", false, headers).storePath); downloadFile(store, boostfmt("%s/info/refs", base_url), "source", false, headers).storePath);
std::ifstream is(file); std::ifstream is(file);
std::string line; std::string line;
@ -421,14 +421,14 @@ struct SourceHutInputScheme : GitArchiveInputScheme
throw BadURL("in '%d', couldn't find ref '%d'", input.to_string(), ref); throw BadURL("in '%d', couldn't find ref '%d'", input.to_string(), ref);
auto rev = Hash::parseAny(*id, htSHA1); auto rev = Hash::parseAny(*id, htSHA1);
debug("HEAD revision for '%s' is %s", fmt("%s/%s", base_url, ref), rev.gitRev()); debug("HEAD revision for '%s' is %s", boostfmt("%s/%s", base_url, ref), rev.gitRev());
return rev; return rev;
} }
DownloadUrl getDownloadUrl(const Input & input) const override DownloadUrl getDownloadUrl(const Input & input) const override
{ {
auto host = maybeGetStrAttr(input.attrs, "host").value_or("git.sr.ht"); auto host = maybeGetStrAttr(input.attrs, "host").value_or("git.sr.ht");
auto url = fmt("https://%s/%s/%s/archive/%s.tar.gz", auto url = boostfmt("https://%s/%s/%s/archive/%s.tar.gz",
host, getStrAttr(input.attrs, "owner"), getStrAttr(input.attrs, "repo"), host, getStrAttr(input.attrs, "owner"), getStrAttr(input.attrs, "repo"),
input.getRev()->to_string(Base16, false)); input.getRev()->to_string(Base16, false));
@ -439,7 +439,7 @@ struct SourceHutInputScheme : GitArchiveInputScheme
void clone(const Input & input, const Path & destDir) const override void clone(const Input & input, const Path & destDir) const override
{ {
auto host = maybeGetStrAttr(input.attrs, "host").value_or("git.sr.ht"); auto host = maybeGetStrAttr(input.attrs, "host").value_or("git.sr.ht");
Input::fromURL(fmt("git+https://%s/%s/%s", Input::fromURL(boostfmt("git+https://%s/%s/%s",
host, getStrAttr(input.attrs, "owner"), getStrAttr(input.attrs, "repo"))) host, getStrAttr(input.attrs, "owner"), getStrAttr(input.attrs, "repo")))
.applyOverrides(input.getRef(), input.getRev()) .applyOverrides(input.getRef(), input.getRev())
.clone(destDir); .clone(destDir);

View file

@ -260,7 +260,7 @@ struct MercurialInputScheme : InputScheme
} }
} }
Path cacheDir = fmt("%s/nix/hg/%s", getCacheDir(), hashString(htSHA256, actualUrl).to_string(Base32, false)); Path cacheDir = boostfmt("%s/nix/hg/%s", getCacheDir(), hashString(htSHA256, actualUrl).to_string(Base32, false));
/* If this is a commit hash that we already have, we don't /* If this is a commit hash that we already have, we don't
have to pull again. */ have to pull again. */
@ -268,7 +268,7 @@ struct MercurialInputScheme : InputScheme
&& pathExists(cacheDir) && pathExists(cacheDir)
&& runProgram(hgOptions({ "log", "-R", cacheDir, "-r", input.getRev()->gitRev(), "--template", "1" })).second == "1")) && runProgram(hgOptions({ "log", "-R", cacheDir, "-r", input.getRev()->gitRev(), "--template", "1" })).second == "1"))
{ {
Activity act(*logger, lvlTalkative, actUnknown, fmt("fetching Mercurial repository '%s'", actualUrl)); Activity act(*logger, lvlTalkative, actUnknown, boostfmt("fetching Mercurial repository '%s'", actualUrl));
if (pathExists(cacheDir)) { if (pathExists(cacheDir)) {
try { try {

View file

@ -119,7 +119,7 @@ struct PathInputScheme : InputScheme
} else } else
absPath = path; absPath = path;
Activity act(*logger, lvlTalkative, actUnknown, fmt("copying '%s'", absPath)); Activity act(*logger, lvlTalkative, actUnknown, boostfmt("copying '%s'", absPath));
// FIXME: check whether access to 'path' is allowed. // FIXME: check whether access to 'path' is allowed.
auto storePath = store->maybeParseStorePath(absPath); auto storePath = store->maybeParseStorePath(absPath);

View file

@ -51,7 +51,7 @@ MixCommonArgs::MixCommonArgs(const std::string & programName)
globalConfig.getSettings(settings); globalConfig.getSettings(settings);
for (auto & s : settings) for (auto & s : settings)
if (s.first.starts_with(prefix)) if (s.first.starts_with(prefix))
completions.add(s.first, fmt("Set the `%s` setting.", s.first)); completions.add(s.first, boostfmt("Set the `%s` setting.", s.first));
} }
} }
}); });

View file

@ -156,10 +156,10 @@ void ProgressBar::startActivity(
std::string name(storePathToName(getS(fields, 0))); std::string name(storePathToName(getS(fields, 0)));
if (name.ends_with(".drv")) if (name.ends_with(".drv"))
name = name.substr(0, name.size() - 4); name = name.substr(0, name.size() - 4);
i->s = fmt("building " ANSI_BOLD "%s" ANSI_NORMAL, name); i->s = boostfmt("building " ANSI_BOLD "%s" ANSI_NORMAL, name);
auto machineName = getS(fields, 1); auto machineName = getS(fields, 1);
if (machineName != "") if (machineName != "")
i->s += fmt(" on " ANSI_BOLD "%s" ANSI_NORMAL, machineName); i->s += boostfmt(" on " ANSI_BOLD "%s" ANSI_NORMAL, machineName);
// Used to be curRound and nrRounds, but the // Used to be curRound and nrRounds, but the
// implementation was broken for a long time. // implementation was broken for a long time.
@ -172,7 +172,7 @@ void ProgressBar::startActivity(
if (type == actSubstitute) { if (type == actSubstitute) {
auto name = storePathToName(getS(fields, 0)); auto name = storePathToName(getS(fields, 0));
auto sub = getS(fields, 1); auto sub = getS(fields, 1);
i->s = fmt( i->s = boostfmt(
sub.starts_with("local") sub.starts_with("local")
? "copying " ANSI_BOLD "%s" ANSI_NORMAL " from %s" ? "copying " ANSI_BOLD "%s" ANSI_NORMAL " from %s"
: "fetching " ANSI_BOLD "%s" ANSI_NORMAL " from %s", : "fetching " ANSI_BOLD "%s" ANSI_NORMAL " from %s",
@ -183,13 +183,13 @@ void ProgressBar::startActivity(
auto name = storePathToName(getS(fields, 0)); auto name = storePathToName(getS(fields, 0));
if (name.ends_with(".drv")) if (name.ends_with(".drv"))
name = name.substr(0, name.size() - 4); name = name.substr(0, name.size() - 4);
i->s = fmt("post-build " ANSI_BOLD "%s" ANSI_NORMAL, name); i->s = boostfmt("post-build " ANSI_BOLD "%s" ANSI_NORMAL, name);
i->name = DrvName(name).name; i->name = DrvName(name).name;
} }
if (type == actQueryPathInfo) { if (type == actQueryPathInfo) {
auto name = storePathToName(getS(fields, 0)); auto name = storePathToName(getS(fields, 0));
i->s = fmt("querying " ANSI_BOLD "%s" ANSI_NORMAL " on %s", name, getS(fields, 1)); i->s = boostfmt("querying " ANSI_BOLD "%s" ANSI_NORMAL " on %s", name, getS(fields, 1));
} }
if ((type == actFileTransfer && hasAncestor(*state, actCopyPath, parent)) if ((type == actFileTransfer && hasAncestor(*state, actCopyPath, parent))
@ -322,7 +322,7 @@ void ProgressBar::eraseProgressDisplay(State & state)
{ {
if (printMultiline && (state.lastLines >= 1)) { if (printMultiline && (state.lastLines >= 1)) {
// FIXME: make sure this works on windows // FIXME: make sure this works on windows
writeToStderr(fmt("\e[G\e[%dF\e[J", state.lastLines)); writeToStderr(boostfmt("\e[G\e[%dF\e[J", state.lastLines));
} else { } else {
writeToStderr("\r\e[K"); writeToStderr("\r\e[K");
} }
@ -406,7 +406,7 @@ std::chrono::milliseconds ProgressBar::draw(State & state, const std::optional<s
} }
if (printMultiline && moreActivities) if (printMultiline && moreActivities)
writeToStderr(fmt("And %d more...", moreActivities)); writeToStderr(boostfmt("And %d more...", moreActivities));
if (!printMultiline) { if (!printMultiline) {
if (!line.empty()) { if (!line.empty()) {
@ -444,19 +444,19 @@ std::string ProgressBar::getStatus(State & state)
if (running || done || expected || failed) { if (running || done || expected || failed) {
if (running) { if (running) {
if (expected != 0) { if (expected != 0) {
auto const runningPart = fmt(numberFmt, running / unit); auto const runningPart = boostfmt(numberFmt, running / unit);
auto const donePart = fmt(numberFmt, done / unit); auto const donePart = boostfmt(numberFmt, done / unit);
auto const expectedPart = fmt(numberFmt, expected / unit); auto const expectedPart = boostfmt(numberFmt, expected / unit);
rendered = fmt( rendered = boostfmt(
ANSI_BLUE "%s" ANSI_NORMAL "/" ANSI_GREEN "%s" ANSI_NORMAL "/%s", ANSI_BLUE "%s" ANSI_NORMAL "/" ANSI_GREEN "%s" ANSI_NORMAL "/%s",
runningPart, runningPart,
donePart, donePart,
expectedPart expectedPart
); );
} else { } else {
auto const runningPart = fmt(numberFmt, running / unit); auto const runningPart = boostfmt(numberFmt, running / unit);
auto const donePart = fmt(numberFmt, done / unit); auto const donePart = boostfmt(numberFmt, done / unit);
rendered = fmt( rendered = boostfmt(
ANSI_BLUE "%s" ANSI_NORMAL "/" ANSI_GREEN "%s" ANSI_NORMAL, ANSI_BLUE "%s" ANSI_NORMAL "/" ANSI_GREEN "%s" ANSI_NORMAL,
runningPart, runningPart,
donePart donePart
@ -464,19 +464,19 @@ std::string ProgressBar::getStatus(State & state)
} }
} else if (expected != done) { } else if (expected != done) {
if (expected != 0) { if (expected != 0) {
auto const donePart = fmt(numberFmt, done / unit); auto const donePart = boostfmt(numberFmt, done / unit);
auto const expectedPart = fmt(numberFmt, expected / unit); auto const expectedPart = boostfmt(numberFmt, expected / unit);
rendered = fmt( rendered = boostfmt(
ANSI_GREEN "%s" ANSI_NORMAL "/%s", ANSI_GREEN "%s" ANSI_NORMAL "/%s",
donePart, donePart,
expectedPart expectedPart
); );
} else { } else {
auto const donePart = fmt(numberFmt, done / unit); auto const donePart = boostfmt(numberFmt, done / unit);
rendered = fmt(ANSI_GREEN "%s" ANSI_NORMAL, donePart); rendered = boostfmt(ANSI_GREEN "%s" ANSI_NORMAL, donePart);
} }
} else { } else {
auto const donePart = fmt(numberFmt, done / unit); auto const donePart = boostfmt(numberFmt, done / unit);
// We only color if `done` is non-zero. // We only color if `done` is non-zero.
if (done) { if (done) {
@ -485,10 +485,10 @@ std::string ProgressBar::getStatus(State & state)
rendered = donePart; rendered = donePart;
} }
} }
rendered = fmt(itemFmt, rendered); rendered = boostfmt(itemFmt, rendered);
if (failed) if (failed)
rendered += fmt(" (" ANSI_RED "%d failed" ANSI_NORMAL ")", failed / unit); rendered += boostfmt(" (" ANSI_RED "%d failed" ANSI_NORMAL ")", failed / unit);
} }
return rendered; return rendered;
@ -517,7 +517,7 @@ std::string ProgressBar::getStatus(State & state)
{ {
auto s = renderActivity(actOptimiseStore, "%s paths optimised"); auto s = renderActivity(actOptimiseStore, "%s paths optimised");
if (s != "") { if (s != "") {
s += fmt(", %.1f MiB / %d inodes freed", state.bytesLinked / MiB, state.filesLinked); s += boostfmt(", %.1f MiB / %d inodes freed", state.bytesLinked / MiB, state.filesLinked);
if (!res.empty()) res += ", "; if (!res.empty()) res += ", ";
res += s; res += s;
} }
@ -528,12 +528,12 @@ std::string ProgressBar::getStatus(State & state)
if (state.corruptedPaths) { if (state.corruptedPaths) {
if (!res.empty()) res += ", "; if (!res.empty()) res += ", ";
res += fmt(ANSI_RED "%d corrupted" ANSI_NORMAL, state.corruptedPaths); res += boostfmt(ANSI_RED "%d corrupted" ANSI_NORMAL, state.corruptedPaths);
} }
if (state.untrustedPaths) { if (state.untrustedPaths) {
if (!res.empty()) res += ", "; if (!res.empty()) res += ", ";
res += fmt(ANSI_RED "%d untrusted" ANSI_NORMAL, state.untrustedPaths); res += boostfmt(ANSI_RED "%d untrusted" ANSI_NORMAL, state.untrustedPaths);
} }
return res; return res;
@ -557,7 +557,7 @@ std::optional<char> ProgressBar::ask(std::string_view msg)
{ {
auto state(state_.lock()); auto state(state_.lock());
if (state->paused > 0 || !isatty(STDIN_FILENO)) return {}; if (state->paused > 0 || !isatty(STDIN_FILENO)) return {};
std::cerr << fmt("\r\e[K%s ", msg); std::cerr << boostfmt("\r\e[K%s ", msg);
auto s = trim(readLine(STDIN_FILENO)); auto s = trim(readLine(STDIN_FILENO));
if (s.size() != 1) return {}; if (s.size() != 1) return {};
draw(*state, {}); draw(*state, {});

View file

@ -280,7 +280,7 @@ void parseCmdLine(const std::string & programName, const Strings & args,
void printVersion(const std::string & programName) void printVersion(const std::string & programName)
{ {
std::cout << fmt("%1% (Lix, like Nix) %2%", programName, nixVersion) << std::endl; std::cout << boostfmt("%1% (Lix, like Nix) %2%", programName, nixVersion) << std::endl;
if (verbosity > lvlNotice) { if (verbosity > lvlNotice) {
Strings cfg; Strings cfg;
#if HAVE_BOEHMGC #if HAVE_BOEHMGC
@ -391,7 +391,7 @@ RunPager::~RunPager()
PrintFreed::~PrintFreed() PrintFreed::~PrintFreed()
{ {
if (show) if (show)
std::cout << fmt("%d store paths deleted, %s freed\n", std::cout << boostfmt("%d store paths deleted, %s freed\n",
results.paths.size(), results.paths.size(),
showBytes(results.bytesFreed)); showBytes(results.bytesFreed));
} }

View file

@ -354,7 +354,7 @@ std::shared_ptr<const ValidPathInfo> BinaryCacheStore::queryPathInfoUncached(con
auto uri = getUri(); auto uri = getUri();
auto storePathS = printStorePath(storePath); auto storePathS = printStorePath(storePath);
auto act = std::make_shared<Activity>(*logger, lvlTalkative, actQueryPathInfo, auto act = std::make_shared<Activity>(*logger, lvlTalkative, actQueryPathInfo,
fmt("querying info about '%s' on '%s'", storePathS, uri), Logger::Fields{storePathS, uri}); boostfmt("querying info about '%s' on '%s'", storePathS, uri), Logger::Fields{storePathS, uri});
PushActivity pact(act->id); PushActivity pact(act->id);
auto narInfoFile = narInfoFileFor(storePath); auto narInfoFile = narInfoFileFor(storePath);

View file

@ -71,7 +71,7 @@ DerivationGoal::DerivationGoal(const StorePath & drvPath,
, buildMode(buildMode) , buildMode(buildMode)
{ {
state = &DerivationGoal::getDerivation; state = &DerivationGoal::getDerivation;
name = fmt( name = boostfmt(
"building of '%s' from .drv file", "building of '%s' from .drv file",
DerivedPath::Built { makeConstantStorePathRef(drvPath), wantedOutputs }.to_string(worker.store)); DerivedPath::Built { makeConstantStorePathRef(drvPath), wantedOutputs }.to_string(worker.store));
trace("created"); trace("created");
@ -92,7 +92,7 @@ DerivationGoal::DerivationGoal(const StorePath & drvPath, const BasicDerivation
this->drv = std::make_unique<Derivation>(drv); this->drv = std::make_unique<Derivation>(drv);
state = &DerivationGoal::haveDerivation; state = &DerivationGoal::haveDerivation;
name = fmt( name = boostfmt(
"building of '%s' from in-memory derivation", "building of '%s' from in-memory derivation",
DerivedPath::Built { makeConstantStorePathRef(drvPath), drv.outputNames() }.to_string(worker.store)); DerivedPath::Built { makeConstantStorePathRef(drvPath), drv.outputNames() }.to_string(worker.store));
trace("created"); trace("created");
@ -577,7 +577,7 @@ void DerivationGoal::inputsRealised()
auto pathResolved = writeDerivation(worker.store, drvResolved); auto pathResolved = writeDerivation(worker.store, drvResolved);
auto msg = fmt("resolved derivation: '%s' -> '%s'", auto msg = boostfmt("resolved derivation: '%s' -> '%s'",
worker.store.printStorePath(drvPath), worker.store.printStorePath(drvPath),
worker.store.printStorePath(pathResolved)); worker.store.printStorePath(pathResolved));
act = std::make_unique<Activity>(*logger, lvlInfo, actBuildWaiting, msg, act = std::make_unique<Activity>(*logger, lvlInfo, actBuildWaiting, msg,
@ -661,12 +661,12 @@ void DerivationGoal::inputsRealised()
void DerivationGoal::started() void DerivationGoal::started()
{ {
auto msg = fmt( auto msg = boostfmt(
buildMode == bmRepair ? "repairing outputs of '%s'" : buildMode == bmRepair ? "repairing outputs of '%s'" :
buildMode == bmCheck ? "checking outputs of '%s'" : buildMode == bmCheck ? "checking outputs of '%s'" :
"building '%s'", worker.store.printStorePath(drvPath)); "building '%s'", worker.store.printStorePath(drvPath));
fmt("building '%s'", worker.store.printStorePath(drvPath)); boostfmt("building '%s'", worker.store.printStorePath(drvPath));
if (hook) msg += fmt(" on '%s'", machineName); if (hook) msg += boostfmt(" on '%s'", machineName);
act = std::make_unique<Activity>(*logger, lvlInfo, actBuild, msg, act = std::make_unique<Activity>(*logger, lvlInfo, actBuild, msg,
Logger::Fields{worker.store.printStorePath(drvPath), hook ? machineName : "", 1, 1}); Logger::Fields{worker.store.printStorePath(drvPath), hook ? machineName : "", 1, 1});
mcRunningBuilds = std::make_unique<MaintainCount<uint64_t>>(worker.runningBuilds); mcRunningBuilds = std::make_unique<MaintainCount<uint64_t>>(worker.runningBuilds);
@ -707,7 +707,7 @@ void DerivationGoal::tryToBuild()
if (!outputLocks.lockPaths(lockFiles, "", false)) { if (!outputLocks.lockPaths(lockFiles, "", false)) {
if (!actLock) if (!actLock)
actLock = std::make_unique<Activity>(*logger, lvlWarn, actBuildWaiting, actLock = std::make_unique<Activity>(*logger, lvlWarn, actBuildWaiting,
fmt("waiting for lock on %s", Magenta(showPaths(lockFiles)))); boostfmt("waiting for lock on %s", Magenta(showPaths(lockFiles))));
worker.waitForAWhile(shared_from_this()); worker.waitForAWhile(shared_from_this());
return; return;
} }
@ -761,7 +761,7 @@ void DerivationGoal::tryToBuild()
the wake-up timeout expires. */ the wake-up timeout expires. */
if (!actLock) if (!actLock)
actLock = std::make_unique<Activity>(*logger, lvlTalkative, actBuildWaiting, actLock = std::make_unique<Activity>(*logger, lvlTalkative, actBuildWaiting,
fmt("waiting for a machine to build '%s'", Magenta(worker.store.printStorePath(drvPath)))); boostfmt("waiting for a machine to build '%s'", Magenta(worker.store.printStorePath(drvPath))));
worker.waitForAWhile(shared_from_this()); worker.waitForAWhile(shared_from_this());
outputLocks.unlock(); outputLocks.unlock();
return; return;
@ -810,7 +810,7 @@ void replaceValidPath(const Path & storePath, const Path & tmpPath)
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
we're repairing (say) Glibc, we end up with a broken system. */ we're repairing (say) Glibc, we end up with a broken system. */
Path oldPath = fmt("%1%.old-%2%-%3%", storePath, getpid(), random()); Path oldPath = boostfmt("%1%.old-%2%-%3%", storePath, getpid(), random());
if (pathExists(storePath)) if (pathExists(storePath))
movePath(storePath, oldPath); movePath(storePath, oldPath);
@ -884,7 +884,7 @@ void runPostBuildHook(
return; return;
Activity act(logger, lvlTalkative, actPostBuildHook, Activity act(logger, lvlTalkative, actPostBuildHook,
fmt("running post-build-hook '%s'", settings.postBuildHook), boostfmt("running post-build-hook '%s'", settings.postBuildHook),
Logger::Fields{store.printStorePath(drvPath)}); Logger::Fields{store.printStorePath(drvPath)});
PushActivity pact(act.id); PushActivity pact(act.id);
std::map<std::string, std::string> hookEnvironment = getEnv(); std::map<std::string, std::string> hookEnvironment = getEnv();
@ -978,12 +978,12 @@ void DerivationGoal::buildDone()
diskFull |= cleanupDecideWhetherDiskFull(); diskFull |= cleanupDecideWhetherDiskFull();
auto msg = fmt("builder for '%s' %s", auto msg = boostfmt("builder for '%s' %s",
Magenta(worker.store.printStorePath(drvPath)), Magenta(worker.store.printStorePath(drvPath)),
statusToString(status)); statusToString(status));
if (!logger->isVerbose() && !logTail.empty()) { if (!logger->isVerbose() && !logTail.empty()) {
msg += fmt(";\nlast %d log lines:\n", logTail.size()); msg += boostfmt(";\nlast %d log lines:\n", logTail.size());
for (auto & line : logTail) { for (auto & line : logTail) {
msg += "> "; msg += "> ";
msg += line; msg += line;
@ -992,7 +992,7 @@ void DerivationGoal::buildDone()
auto nixLogCommand = experimentalFeatureSettings.isEnabled(Xp::NixCommand) auto nixLogCommand = experimentalFeatureSettings.isEnabled(Xp::NixCommand)
? "nix log" ? "nix log"
: "nix-store -l"; : "nix-store -l";
msg += fmt("For full logs, run '" ANSI_BOLD "%s %s" ANSI_NORMAL "'.", msg += boostfmt("For full logs, run '" ANSI_BOLD "%s %s" ANSI_NORMAL "'.",
nixLogCommand, nixLogCommand,
worker.store.printStorePath(drvPath)); worker.store.printStorePath(drvPath));
} }
@ -1259,10 +1259,10 @@ Path DerivationGoal::openLogFile()
logDir = localStore->logDir; logDir = localStore->logDir;
else else
logDir = settings.nixLogDir; logDir = settings.nixLogDir;
Path dir = fmt("%s/%s/%s/", logDir, LocalFSStore::drvsLogDir, baseName.substr(0, 2)); Path dir = boostfmt("%s/%s/%s/", logDir, LocalFSStore::drvsLogDir, baseName.substr(0, 2));
createDirs(dir); createDirs(dir);
Path logFileName = fmt("%s/%s%s", dir, baseName.substr(2), Path logFileName = boostfmt("%s/%s%s", dir, baseName.substr(2),
settings.compressLog ? ".bz2" : ""); settings.compressLog ? ".bz2" : "");
fdLogFile = AutoCloseFD{open(logFileName.c_str(), O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC, 0666)}; fdLogFile = AutoCloseFD{open(logFileName.c_str(), O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC, 0666)};
@ -1515,7 +1515,7 @@ void DerivationGoal::done(
outputLocks.unlock(); outputLocks.unlock();
buildResult.status = status; buildResult.status = status;
if (ex) if (ex)
buildResult.errorMsg = fmt("%s", Uncolored(ex->info().msg)); buildResult.errorMsg = boostfmt("%s", Uncolored(ex->info().msg));
if (buildResult.status == BuildResult::TimedOut) if (buildResult.status == BuildResult::TimedOut)
worker.timedOut = true; worker.timedOut = true;
if (buildResult.status == BuildResult::PermanentFailure) if (buildResult.status == BuildResult::PermanentFailure)

View file

@ -15,7 +15,7 @@ DrvOutputSubstitutionGoal::DrvOutputSubstitutionGoal(
, id(id) , id(id)
{ {
state = &DrvOutputSubstitutionGoal::init; state = &DrvOutputSubstitutionGoal::init;
name = fmt("substitution of '%s'", id.to_string()); name = boostfmt("substitution of '%s'", id.to_string());
trace("created"); trace("created");
} }

View file

@ -54,7 +54,7 @@ void Goal::waiteeDone(GoalPtr waitee, ExitCode result)
assert(waitees.count(waitee)); assert(waitees.count(waitee));
waitees.erase(waitee); waitees.erase(waitee);
trace(fmt("waitee '%s' done; %d left", waitee->name, waitees.size())); trace(boostfmt("waitee '%s' done; %d left", waitee->name, waitees.size()));
if (result == ecFailed || result == ecNoSubstituters || result == ecIncompleteClosure) ++nrFailed; if (result == ecFailed || result == ecNoSubstituters || result == ecIncompleteClosure) ++nrFailed;

View file

@ -218,7 +218,7 @@ void LocalDerivationGoal::tryLocalBuild()
if (!buildUser) { if (!buildUser) {
if (!actLock) if (!actLock)
actLock = std::make_unique<Activity>(*logger, lvlWarn, actBuildWaiting, actLock = std::make_unique<Activity>(*logger, lvlWarn, actBuildWaiting,
fmt("waiting for a free build user ID for '%s'", Magenta(worker.store.printStorePath(drvPath)))); boostfmt("waiting for a free build user ID for '%s'", Magenta(worker.store.printStorePath(drvPath))));
worker.waitForAWhile(shared_from_this()); worker.waitForAWhile(shared_from_this());
return; return;
} }
@ -452,8 +452,8 @@ void LocalDerivationGoal::startBuilder()
static std::atomic<unsigned int> counter{0}; static std::atomic<unsigned int> counter{0};
cgroup = buildUser cgroup = buildUser
? fmt("%s/nix-build-uid-%d", ourCgroupPath, buildUser->getUID()) ? boostfmt("%s/nix-build-uid-%d", ourCgroupPath, buildUser->getUID())
: fmt("%s/nix-build-pid-%d-%d", ourCgroupPath, getpid(), counter++); : boostfmt("%s/nix-build-pid-%d-%d", ourCgroupPath, getpid(), counter++);
debug("using cgroup '%s'", *cgroup); debug("using cgroup '%s'", *cgroup);
@ -464,7 +464,7 @@ void LocalDerivationGoal::startBuilder()
auto cgroupsDir = settings.nixStateDir + "/cgroups"; auto cgroupsDir = settings.nixStateDir + "/cgroups";
createDirs(cgroupsDir); createDirs(cgroupsDir);
auto cgroupFile = fmt("%s/%d", cgroupsDir, buildUser->getUID()); auto cgroupFile = boostfmt("%s/%d", cgroupsDir, buildUser->getUID());
if (pathExists(cgroupFile)) { if (pathExists(cgroupFile)) {
auto prevCgroup = readFile(cgroupFile); auto prevCgroup = readFile(cgroupFile);
@ -932,7 +932,7 @@ void LocalDerivationGoal::startBuilder()
pid_t child = startProcess([&]() { runChild(); }, options).release(); pid_t child = startProcess([&]() { runChild(); }, options).release();
writeFull(sendPid.writeSide.get(), fmt("%d\n", child)); writeFull(sendPid.writeSide.get(), boostfmt("%d\n", child));
_exit(0); _exit(0);
}); });
@ -962,20 +962,20 @@ void LocalDerivationGoal::startBuilder()
uid_t nrIds = buildUser ? buildUser->getUIDCount() : 1; uid_t nrIds = buildUser ? buildUser->getUIDCount() : 1;
writeFile("/proc/" + std::to_string(pid.get()) + "/uid_map", writeFile("/proc/" + std::to_string(pid.get()) + "/uid_map",
fmt("%d %d %d", sandboxUid(), hostUid, nrIds)); boostfmt("%d %d %d", sandboxUid(), hostUid, nrIds));
if (!buildUser || buildUser->getUIDCount() == 1) if (!buildUser || buildUser->getUIDCount() == 1)
writeFile("/proc/" + std::to_string(pid.get()) + "/setgroups", "deny"); writeFile("/proc/" + std::to_string(pid.get()) + "/setgroups", "deny");
writeFile("/proc/" + std::to_string(pid.get()) + "/gid_map", writeFile("/proc/" + std::to_string(pid.get()) + "/gid_map",
fmt("%d %d %d", sandboxGid(), hostGid, nrIds)); boostfmt("%d %d %d", sandboxGid(), hostGid, nrIds));
} else { } else {
debug("note: not using a user namespace"); debug("note: not using a user namespace");
} }
/* Now that we now the sandbox uid, we can write /* Now that we now the sandbox uid, we can write
/etc/passwd. */ /etc/passwd. */
writeFile(chrootRootDir + "/etc/passwd", fmt( writeFile(chrootRootDir + "/etc/passwd", boostfmt(
"root:x:0:0:Nix build user:%3%:/noshell\n" "root:x:0:0:Nix build user:%3%:/noshell\n"
"nixbld:x:%1%:%2%:Nix build user:%3%:/noshell\n" "nixbld:x:%1%:%2%:Nix build user:%3%:/noshell\n"
"nobody:x:65534:65534:Nobody:/:/noshell\n", "nobody:x:65534:65534:Nobody:/:/noshell\n",
@ -984,25 +984,25 @@ void LocalDerivationGoal::startBuilder()
/* Declare the build user's group so that programs get a consistent /* Declare the build user's group so that programs get a consistent
view of the system (e.g., "id -gn"). */ view of the system (e.g., "id -gn"). */
writeFile(chrootRootDir + "/etc/group", writeFile(chrootRootDir + "/etc/group",
fmt("root:x:0:\n" boostfmt("root:x:0:\n"
"nixbld:!:%1%:\n" "nixbld:!:%1%:\n"
"nogroup:x:65534:\n", sandboxGid())); "nogroup:x:65534:\n", sandboxGid()));
/* Save the mount- and user namespace of the child. We have to do this /* Save the mount- and user namespace of the child. We have to do this
*before* the child does a chroot. */ *before* the child does a chroot. */
sandboxMountNamespace = AutoCloseFD{open(fmt("/proc/%d/ns/mnt", pid.get()).c_str(), O_RDONLY)}; sandboxMountNamespace = AutoCloseFD{open(boostfmt("/proc/%d/ns/mnt", pid.get()).c_str(), O_RDONLY)};
if (sandboxMountNamespace.get() == -1) if (sandboxMountNamespace.get() == -1)
throw SysError("getting sandbox mount namespace"); throw SysError("getting sandbox mount namespace");
if (usingUserNamespace) { if (usingUserNamespace) {
sandboxUserNamespace = AutoCloseFD{open(fmt("/proc/%d/ns/user", pid.get()).c_str(), O_RDONLY)}; sandboxUserNamespace = AutoCloseFD{open(boostfmt("/proc/%d/ns/user", pid.get()).c_str(), O_RDONLY)};
if (sandboxUserNamespace.get() == -1) if (sandboxUserNamespace.get() == -1)
throw SysError("getting sandbox user namespace"); throw SysError("getting sandbox user namespace");
} }
/* Move the child into its own cgroup. */ /* Move the child into its own cgroup. */
if (cgroup) if (cgroup)
writeFile(*cgroup + "/cgroup.procs", fmt("%d", pid.get())); writeFile(*cgroup + "/cgroup.procs", boostfmt("%d", pid.get()));
/* Signal the builder that we've updated its user namespace. */ /* Signal the builder that we've updated its user namespace. */
writeFull(userNamespaceSync.writeSide.get(), "1"); writeFull(userNamespaceSync.writeSide.get(), "1");
@ -1121,7 +1121,7 @@ void LocalDerivationGoal::initEnv()
env["NIX_STORE"] = worker.store.storeDir; env["NIX_STORE"] = worker.store.storeDir;
/* The maximum number of cores to utilize for parallel building. */ /* The maximum number of cores to utilize for parallel building. */
env["NIX_BUILD_CORES"] = fmt("%d", settings.buildCores); env["NIX_BUILD_CORES"] = boostfmt("%d", settings.buildCores);
initTmpDir(); initTmpDir();
@ -1877,7 +1877,7 @@ void LocalDerivationGoal::runChild()
/* Mount a new tmpfs on /dev/shm to ensure that whatever /* Mount a new tmpfs on /dev/shm to ensure that whatever
the builder puts in /dev/shm is cleaned up automatically. */ the builder puts in /dev/shm is cleaned up automatically. */
if (pathExists("/dev/shm") && mount("none", (chrootRootDir + "/dev/shm").c_str(), "tmpfs", 0, if (pathExists("/dev/shm") && mount("none", (chrootRootDir + "/dev/shm").c_str(), "tmpfs", 0,
fmt("size=%s", settings.sandboxShmSize).c_str()) == -1) boostfmt("size=%s", settings.sandboxShmSize).c_str()) == -1)
throw SysError("mounting /dev/shm"); throw SysError("mounting /dev/shm");
/* Mount a new devpts on /dev/pts. Note that this /* Mount a new devpts on /dev/pts. Note that this
@ -2059,7 +2059,7 @@ void LocalDerivationGoal::runChild()
/* Add the output paths we'll use at build-time to the chroot */ /* Add the output paths we'll use at build-time to the chroot */
sandboxProfile += "(allow file-read* file-write* process-exec\n"; sandboxProfile += "(allow file-read* file-write* process-exec\n";
for (auto & [_, path] : scratchOutputs) for (auto & [_, path] : scratchOutputs)
sandboxProfile += fmt("\t(subpath \"%s\")\n", worker.store.printStorePath(path)); sandboxProfile += boostfmt("\t(subpath \"%s\")\n", worker.store.printStorePath(path));
sandboxProfile += ")\n"; sandboxProfile += ")\n";
@ -2082,16 +2082,16 @@ void LocalDerivationGoal::runChild()
throw SysError("getting attributes of path '%s", path); throw SysError("getting attributes of path '%s", path);
} }
if (S_ISDIR(st.st_mode)) if (S_ISDIR(st.st_mode))
sandboxProfile += fmt("\t(subpath \"%s\")\n", path); sandboxProfile += boostfmt("\t(subpath \"%s\")\n", path);
else else
sandboxProfile += fmt("\t(literal \"%s\")\n", path); sandboxProfile += boostfmt("\t(literal \"%s\")\n", path);
} }
sandboxProfile += ")\n"; sandboxProfile += ")\n";
/* Allow file-read* on full directory hierarchy to self. Allows realpath() */ /* Allow file-read* on full directory hierarchy to self. Allows realpath() */
sandboxProfile += "(allow file-read*\n"; sandboxProfile += "(allow file-read*\n";
for (auto & i : ancestry) { for (auto & i : ancestry) {
sandboxProfile += fmt("\t(literal \"%s\")\n", i); sandboxProfile += boostfmt("\t(literal \"%s\")\n", i);
} }
sandboxProfile += ")\n"; sandboxProfile += ")\n";

View file

@ -13,7 +13,7 @@ PathSubstitutionGoal::PathSubstitutionGoal(const StorePath & storePath, Worker &
, ca(ca) , ca(ca)
{ {
state = &PathSubstitutionGoal::init; state = &PathSubstitutionGoal::init;
name = fmt("substitution of '%s'", worker.store.printStorePath(this->storePath)); name = boostfmt("substitution of '%s'", worker.store.printStorePath(this->storePath));
trace("created"); trace("created");
maintainExpectedSubstitutions = std::make_unique<MaintainCount<uint64_t>>(worker.expectedSubstitutions); maintainExpectedSubstitutions = std::make_unique<MaintainCount<uint64_t>>(worker.expectedSubstitutions);
} }
@ -82,7 +82,7 @@ void PathSubstitutionGoal::tryNext()
done( done(
substituterFailed ? ecFailed : ecNoSubstituters, substituterFailed ? ecFailed : ecNoSubstituters,
BuildResult::NoSubstituters, BuildResult::NoSubstituters,
fmt("path '%s' is required, but there is no substituter that can build it", worker.store.printStorePath(storePath))); boostfmt("path '%s' is required, but there is no substituter that can build it", worker.store.printStorePath(storePath)));
if (substituterFailed) { if (substituterFailed) {
worker.failedSubstitutions++; worker.failedSubstitutions++;
@ -184,7 +184,7 @@ void PathSubstitutionGoal::referencesValid()
done( done(
nrNoSubstituters > 0 || nrIncompleteClosure > 0 ? ecIncompleteClosure : ecFailed, nrNoSubstituters > 0 || nrIncompleteClosure > 0 ? ecIncompleteClosure : ecFailed,
BuildResult::DependencyFailed, BuildResult::DependencyFailed,
fmt("some references of path '%s' could not be realised", worker.store.printStorePath(storePath))); boostfmt("some references of path '%s' could not be realised", worker.store.printStorePath(storePath)));
return; return;
} }

View file

@ -85,7 +85,7 @@ struct curlFileTransfer : public FileTransfer
: fileTransfer(fileTransfer) : fileTransfer(fileTransfer)
, request(request) , request(request)
, act(*logger, lvlTalkative, actFileTransfer, , act(*logger, lvlTalkative, actFileTransfer,
fmt(request.data ? "uploading '%s'" : "downloading '%s'", request.uri), boostfmt(request.data ? "uploading '%s'" : "downloading '%s'", request.uri),
{request.uri}, request.parentAct) {request.uri}, request.parentAct)
, callback([cb{std::move(callback)}] (std::exception_ptr ex, FileTransferResult r) { , callback([cb{std::move(callback)}] (std::exception_ptr ex, FileTransferResult r) {
cb(ex); cb(ex);
@ -99,7 +99,7 @@ struct curlFileTransfer : public FileTransfer
if (!request.mimeType.empty()) if (!request.mimeType.empty())
requestHeaders = curl_slist_append(requestHeaders, ("Content-Type: " + request.mimeType).c_str()); requestHeaders = curl_slist_append(requestHeaders, ("Content-Type: " + request.mimeType).c_str());
for (auto it = request.headers.begin(); it != request.headers.end(); ++it){ for (auto it = request.headers.begin(); it != request.headers.end(); ++it){
requestHeaders = curl_slist_append(requestHeaders, fmt("%s: %s", it->first, it->second).c_str()); requestHeaders = curl_slist_append(requestHeaders, boostfmt("%s: %s", it->first, it->second).c_str());
} }
} }
@ -415,7 +415,7 @@ struct curlFileTransfer : public FileTransfer
std::move(response), std::move(response),
"unable to %s '%s': HTTP error %d (%s)%s", "unable to %s '%s': HTTP error %d (%s)%s",
request.verb(), request.uri, httpStatus, statusMsg, request.verb(), request.uri, httpStatus, statusMsg,
code == CURLE_OK ? "" : fmt(" (curl error: %s)", curl_easy_strerror(code))) code == CURLE_OK ? "" : boostfmt(" (curl error: %s)", curl_easy_strerror(code)))
: FileTransferError(err, : FileTransferError(err,
std::move(response), std::move(response),
"unable to %s '%s': %s (%d)", "unable to %s '%s': %s (%d)",

View file

@ -32,7 +32,7 @@ static void makeSymlink(const Path & link, const Path & target)
createDirs(dirOf(link)); createDirs(dirOf(link));
/* Create the new symlink. */ /* Create the new symlink. */
Path tempLink = fmt("%1%.tmp-%2%-%3%", link, getpid(), random()); Path tempLink = boostfmt("%1%.tmp-%2%-%3%", link, getpid(), random());
createSymlink(target, tempLink); createSymlink(target, tempLink);
/* Atomically replace the old one. */ /* Atomically replace the old one. */
@ -43,7 +43,7 @@ static void makeSymlink(const Path & link, const Path & target)
void LocalStore::addIndirectRoot(const Path & path) void LocalStore::addIndirectRoot(const Path & path)
{ {
std::string hash = hashString(htSHA1, path).to_string(Base32, false); std::string hash = hashString(htSHA1, path).to_string(Base32, false);
Path realRoot = canonPath(fmt("%1%/%2%/auto/%3%", stateDir, gcRootsDir, hash)); Path realRoot = canonPath(boostfmt("%1%/%2%/auto/%3%", stateDir, gcRootsDir, hash));
makeSymlink(realRoot, path); makeSymlink(realRoot, path);
} }
@ -227,7 +227,7 @@ void LocalStore::findTempRoots(Roots & tempRoots, bool censor)
while ((end = contents.find((char) 0, pos)) != std::string::npos) { while ((end = contents.find((char) 0, pos)) != std::string::npos) {
Path root(contents, pos, end - pos); Path root(contents, pos, end - pos);
debug("got temporary root '%s'", root); debug("got temporary root '%s'", root);
tempRoots[parseStorePath(root)].emplace(censor ? censored : fmt("{temp:%d}", pid)); tempRoots[parseStorePath(root)].emplace(censor ? censored : boostfmt("{temp:%d}", pid));
pos = end + 1; pos = end + 1;
} }
} }

View file

@ -897,7 +897,7 @@ public:
)"}; )"};
Setting<std::string> netrcFile{ Setting<std::string> netrcFile{
this, fmt("%s/%s", nixConfDir, "netrc"), "netrc-file", this, boostfmt("%s/%s", nixConfDir, "netrc"), "netrc-file",
R"( R"(
If set to an absolute path to a `netrc` file, Lix will use the HTTP If set to an absolute path to a `netrc` file, Lix will use the HTTP
authentication credentials in this file when trying to download from authentication credentials in this file when trying to download from

View file

@ -114,7 +114,7 @@ struct LegacySSHStore : public virtual LegacySSHStoreConfig, public virtual Stor
{ {
auto conn = make_ref<Connection>(); auto conn = make_ref<Connection>();
conn->sshConn = master.startCommand( conn->sshConn = master.startCommand(
fmt("%s --serve --write", remoteProgram) boostfmt("%s --serve --write", remoteProgram)
+ (remoteStore.get() == "" ? "" : " --store " + shellEscape(remoteStore.get()))); + (remoteStore.get() == "" ? "" : " --store " + shellEscape(remoteStore.get())));
conn->to = FdSink(conn->sshConn->in.get()); conn->to = FdSink(conn->sshConn->in.get());
conn->from = FdSource(conn->sshConn->out.get()); conn->from = FdSource(conn->sshConn->out.get());

View file

@ -60,7 +60,7 @@ protected:
{ {
auto path2 = binaryCacheDir + "/" + path; auto path2 = binaryCacheDir + "/" + path;
static std::atomic<int> counter{0}; static std::atomic<int> counter{0};
Path tmp = fmt("%s.tmp.%d.%d", path2, getpid(), ++counter); Path tmp = boostfmt("%s.tmp.%d.%d", path2, getpid(), ++counter);
AutoDelete del(tmp, false); AutoDelete del(tmp, false);
StreamToSourceAdapter source(istream); StreamToSourceAdapter source(istream);
writeFile(tmp, source); writeFile(tmp, source);

View file

@ -95,8 +95,8 @@ std::optional<std::string> LocalFSStore::getBuildLogExact(const StorePath & path
Path logPath = Path logPath =
j == 0 j == 0
? fmt("%s/%s/%s/%s", logDir, drvsLogDir, baseName.substr(0, 2), baseName.substr(2)) ? boostfmt("%s/%s/%s/%s", logDir, drvsLogDir, baseName.substr(0, 2), baseName.substr(2))
: fmt("%s/%s/%s", logDir, drvsLogDir, baseName); : boostfmt("%s/%s/%s", logDir, drvsLogDir, baseName);
Path logBz2Path = logPath + ".bz2"; Path logBz2Path = logPath + ".bz2";
if (pathExists(logPath)) if (pathExists(logPath))

View file

@ -168,7 +168,7 @@ void migrateCASchema(SQLite& db, Path schemaPath, AutoCloseFD& lockFd)
txn.commit(); txn.commit();
} }
writeFile(schemaPath, fmt("%d", nixCASchemaVersion), 0666, true); writeFile(schemaPath, boostfmt("%d", nixCASchemaVersion), 0666, true);
lockFile(lockFd.get(), ltRead, true); lockFile(lockFd.get(), ltRead, true);
} }
} }
@ -184,7 +184,7 @@ LocalStore::LocalStore(const Params & params)
, reservedPath(dbDir + "/reserved") , reservedPath(dbDir + "/reserved")
, schemaPath(dbDir + "/schema") , schemaPath(dbDir + "/schema")
, tempRootsDir(stateDir + "/temproots") , tempRootsDir(stateDir + "/temproots")
, fnTempRoots(fmt("%s/%d", tempRootsDir, getpid())) , fnTempRoots(boostfmt("%s/%d", tempRootsDir, getpid()))
, locksHeld(tokenizeString<PathSet>(getEnv("NIX_HELD_LOCKS").value_or(""))) , locksHeld(tokenizeString<PathSet>(getEnv("NIX_HELD_LOCKS").value_or("")))
{ {
auto state(_state.lock()); auto state(_state.lock());
@ -305,7 +305,7 @@ LocalStore::LocalStore(const Params & params)
else if (curSchema == 0) { /* new store */ else if (curSchema == 0) { /* new store */
curSchema = nixSchemaVersion; curSchema = nixSchemaVersion;
openDB(*state, true); openDB(*state, true);
writeFile(schemaPath, fmt("%1%", nixSchemaVersion), 0666, true); writeFile(schemaPath, boostfmt("%1%", nixSchemaVersion), 0666, true);
} }
else if (curSchema < nixSchemaVersion) { else if (curSchema < nixSchemaVersion) {
@ -354,7 +354,7 @@ LocalStore::LocalStore(const Params & params)
txn.commit(); txn.commit();
} }
writeFile(schemaPath, fmt("%1%", nixSchemaVersion), 0666, true); writeFile(schemaPath, boostfmt("%1%", nixSchemaVersion), 0666, true);
lockFile(globalLock.get(), ltRead, true); lockFile(globalLock.get(), ltRead, true);
} }
@ -1915,13 +1915,13 @@ void LocalStore::addBuildLog(const StorePath & drvPath, std::string_view log)
auto baseName = drvPath.to_string(); auto baseName = drvPath.to_string();
auto logPath = fmt("%s/%s/%s/%s.bz2", logDir, drvsLogDir, baseName.substr(0, 2), baseName.substr(2)); auto logPath = boostfmt("%s/%s/%s/%s.bz2", logDir, drvsLogDir, baseName.substr(0, 2), baseName.substr(2));
if (pathExists(logPath)) return; if (pathExists(logPath)) return;
createDirs(dirOf(logPath)); createDirs(dirOf(logPath));
auto tmpFile = fmt("%s.tmp.%d", logPath, getpid()); auto tmpFile = boostfmt("%s.tmp.%d", logPath, getpid());
writeFile(tmpFile, compress("bzip2", log)); writeFile(tmpFile, compress("bzip2", log));

View file

@ -76,7 +76,7 @@ struct SimpleUserLock : UserLock
if (!pw) if (!pw)
throw Error("the user '%s' in the group '%s' does not exist", i, settings.buildUsersGroup); throw Error("the user '%s' in the group '%s' does not exist", i, settings.buildUsersGroup);
auto fnUserLock = fmt("%s/userpool/%s", settings.nixStateDir,pw->pw_uid); auto fnUserLock = boostfmt("%s/userpool/%s", settings.nixStateDir,pw->pw_uid);
AutoCloseFD fd{open(fnUserLock.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0600)}; AutoCloseFD fd{open(fnUserLock.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0600)};
if (!fd) if (!fd)
@ -148,7 +148,7 @@ struct AutoUserLock : UserLock
createDirs(settings.nixStateDir + "/userpool2"); createDirs(settings.nixStateDir + "/userpool2");
auto fnUserLock = fmt("%s/userpool2/slot-%d", settings.nixStateDir, i); auto fnUserLock = boostfmt("%s/userpool2/slot-%d", settings.nixStateDir, i);
AutoCloseFD fd{open(fnUserLock.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0600)}; AutoCloseFD fd{open(fnUserLock.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0600)};
if (!fd) if (!fd)

View file

@ -213,7 +213,7 @@ void LocalStore::optimisePath_(Activity * act, OptimiseStats & stats,
its timestamp back to 0. */ its timestamp back to 0. */
MakeReadOnly makeReadOnly(mustToggle ? dirOfPath : ""); MakeReadOnly makeReadOnly(mustToggle ? dirOfPath : "");
Path tempLink = fmt("%1%/.tmp-link-%2%-%3%", realStoreDir, getpid(), random()); Path tempLink = boostfmt("%1%/.tmp-link-%2%-%3%", realStoreDir, getpid(), random());
if (link(linkPath.c_str(), tempLink.c_str()) == -1) { if (link(linkPath.c_str(), tempLink.c_str()) == -1) {
if (errno == EMLINK) { if (errno == EMLINK) {
@ -268,7 +268,7 @@ void LocalStore::optimiseStore(OptimiseStats & stats)
addTempRoot(i); addTempRoot(i);
if (!isValidPath(i)) continue; /* path was GC'ed, probably */ if (!isValidPath(i)) continue; /* path was GC'ed, probably */
{ {
Activity act(*logger, lvlTalkative, actUnknown, fmt("optimising path '%s'", printStorePath(i))); Activity act(*logger, lvlTalkative, actUnknown, boostfmt("optimising path '%s'", printStorePath(i)));
optimisePath_(&act, stats, realStoreDir + "/" + std::string(i.to_string()), inodeHash, NoRepair); optimisePath_(&act, stats, realStoreDir + "/" + std::string(i.to_string()), inodeHash, NoRepair);
} }
done++; done++;

View file

@ -195,7 +195,7 @@ std::string writeStructuredAttrsShell(const nlohmann::json & json)
auto s = handleSimpleType(value); auto s = handleSimpleType(value);
if (s) if (s)
jsonSh += fmt("declare %s=%s\n", key, *s); jsonSh += boostfmt("declare %s=%s\n", key, *s);
else if (value.is_array()) { else if (value.is_array()) {
std::string s2; std::string s2;
@ -208,7 +208,7 @@ std::string writeStructuredAttrsShell(const nlohmann::json & json)
} }
if (good) if (good)
jsonSh += fmt("declare -a %s=(%s)\n", key, s2); jsonSh += boostfmt("declare -a %s=(%s)\n", key, s2);
} }
else if (value.is_object()) { else if (value.is_object()) {
@ -218,11 +218,11 @@ std::string writeStructuredAttrsShell(const nlohmann::json & json)
for (auto & [key2, value2] : value.items()) { for (auto & [key2, value2] : value.items()) {
auto s3 = handleSimpleType(value2); auto s3 = handleSimpleType(value2);
if (!s3) { good = false; break; } if (!s3) { good = false; break; }
s2 += fmt("[%s]=%s ", shellEscape(key2), *s3); s2 += boostfmt("[%s]=%s ", shellEscape(key2), *s3);
} }
if (good) if (good)
jsonSh += fmt("declare -A %s=(%s)\n", key, s2); jsonSh += boostfmt("declare -A %s=(%s)\n", key, s2);
} }
} }

View file

@ -44,10 +44,10 @@ void DarwinLocalStore::findPlatformRoots(UncheckedRoots & unchecked)
throw SysError("Getting pid %1% working directory", pid); throw SysError("Getting pid %1% working directory", pid);
} }
unchecked[std::string(vnodeInfo.pvi_cdir.vip_path)].emplace(fmt("{libproc/%d/cwd}", pid) unchecked[std::string(vnodeInfo.pvi_cdir.vip_path)].emplace(boostfmt("{libproc/%d/cwd}", pid)
); );
unchecked[std::string(vnodeInfo.pvi_rdir.vip_path)].emplace( unchecked[std::string(vnodeInfo.pvi_rdir.vip_path)].emplace(
fmt("{libproc/%d/rootdir}", pid) boostfmt("{libproc/%d/rootdir}", pid)
); );
// File descriptors // File descriptors
@ -87,7 +87,7 @@ void DarwinLocalStore::findPlatformRoots(UncheckedRoots & unchecked)
} }
unchecked[std::string(fdInfo.pvip.vip_path)].emplace( unchecked[std::string(fdInfo.pvip.vip_path)].emplace(
fmt("{libproc/%d/fd/%d}", pid, fd.proc_fd) boostfmt("{libproc/%d/fd/%d}", pid, fd.proc_fd)
); );
} }
@ -116,7 +116,7 @@ void DarwinLocalStore::findPlatformRoots(UncheckedRoots & unchecked)
} }
unchecked[std::string(regionInfo.prp_vip.vip_path)].emplace( unchecked[std::string(regionInfo.prp_vip.vip_path)].emplace(
fmt("{libproc/%d/region}", pid) boostfmt("{libproc/%d/region}", pid)
); );
nextAddr = regionInfo.prp_prinfo.pri_address + regionInfo.prp_prinfo.pri_size; nextAddr = regionInfo.prp_prinfo.pri_address + regionInfo.prp_prinfo.pri_size;
@ -167,7 +167,7 @@ void DarwinLocalStore::findPlatformRoots(UncheckedRoots & unchecked)
i != env_end; i != env_end;
++i) ++i)
{ {
unchecked[i->str()].emplace(fmt("{libproc/%d/environ}", pid)); unchecked[i->str()].emplace(boostfmt("{libproc/%d/environ}", pid));
} }
}; };
@ -203,7 +203,7 @@ void DarwinLocalStore::findPlatformRoots(UncheckedRoots & unchecked)
} }
unchecked[std::string(threadPathInfo.pvip.vip_path)].emplace( unchecked[std::string(threadPathInfo.pvip.vip_path)].emplace(
fmt("{libproc/%d/thread/%d/cwd}", pid, tid) boostfmt("{libproc/%d/thread/%d/cwd}", pid, tid)
); );
} }
} }

View file

@ -51,10 +51,10 @@ void LinuxLocalStore::findPlatformRoots(UncheckedRoots & unchecked)
checkInterrupt(); checkInterrupt();
if (std::regex_match(ent->d_name, digitsRegex)) { if (std::regex_match(ent->d_name, digitsRegex)) {
try { try {
readProcLink(fmt("/proc/%s/exe", ent->d_name), unchecked); readProcLink(boostfmt("/proc/%s/exe", ent->d_name), unchecked);
readProcLink(fmt("/proc/%s/cwd", ent->d_name), unchecked); readProcLink(boostfmt("/proc/%s/cwd", ent->d_name), unchecked);
auto fdStr = fmt("/proc/%s/fd", ent->d_name); auto fdStr = boostfmt("/proc/%s/fd", ent->d_name);
auto fdDir = AutoCloseDir(opendir(fdStr.c_str())); auto fdDir = AutoCloseDir(opendir(fdStr.c_str()));
if (!fdDir) { if (!fdDir) {
if (errno == ENOENT || errno == EACCES) { if (errno == ENOENT || errno == EACCES) {
@ -65,7 +65,7 @@ void LinuxLocalStore::findPlatformRoots(UncheckedRoots & unchecked)
struct dirent * fd_ent; struct dirent * fd_ent;
while (errno = 0, fd_ent = readdir(fdDir.get())) { while (errno = 0, fd_ent = readdir(fdDir.get())) {
if (fd_ent->d_name[0] != '.') { if (fd_ent->d_name[0] != '.') {
readProcLink(fmt("%s/%s", fdStr, fd_ent->d_name), unchecked); readProcLink(boostfmt("%s/%s", fdStr, fd_ent->d_name), unchecked);
} }
} }
if (errno) { if (errno) {
@ -76,7 +76,7 @@ void LinuxLocalStore::findPlatformRoots(UncheckedRoots & unchecked)
} }
fdDir.reset(); fdDir.reset();
auto mapFile = fmt("/proc/%s/maps", ent->d_name); auto mapFile = boostfmt("/proc/%s/maps", ent->d_name);
auto mapLines = auto mapLines =
tokenizeString<std::vector<std::string>>(readFile(mapFile), "\n"); tokenizeString<std::vector<std::string>>(readFile(mapFile), "\n");
for (const auto & line : mapLines) { for (const auto & line : mapLines) {
@ -86,7 +86,7 @@ void LinuxLocalStore::findPlatformRoots(UncheckedRoots & unchecked)
} }
} }
auto envFile = fmt("/proc/%s/environ", ent->d_name); auto envFile = boostfmt("/proc/%s/environ", ent->d_name);
auto envString = readFile(envFile); auto envString = readFile(envFile);
auto env_end = std::sregex_iterator{}; auto env_end = std::sregex_iterator{};
for (auto i = for (auto i =

View file

@ -67,7 +67,7 @@ std::pair<Generations, std::optional<GenerationNumber>> findGenerations(Path pro
*/ */
static Path makeName(const Path & profile, GenerationNumber num) static Path makeName(const Path & profile, GenerationNumber num)
{ {
return fmt("%s-%s-link", profile, num); return boostfmt("%s-%s-link", profile, num);
} }
@ -294,7 +294,7 @@ void switchGeneration(
void lockProfile(PathLocks & lock, const Path & profile) void lockProfile(PathLocks & lock, const Path & profile)
{ {
lock.lockPaths({profile}, fmt("waiting for lock on profile '%1%'", profile)); lock.lockPaths({profile}, boostfmt("waiting for lock on profile '%1%'", profile));
lock.setDeletion(true); lock.setDeletion(true);
} }

View file

@ -19,7 +19,7 @@ RemoteFSAccessor::RemoteFSAccessor(ref<Store> store, const Path & cacheDir)
Path RemoteFSAccessor::makeCacheFile(std::string_view hashPart, const std::string & ext) Path RemoteFSAccessor::makeCacheFile(std::string_view hashPart, const std::string & ext)
{ {
assert(cacheDir != ""); assert(cacheDir != "");
return fmt("%s/%s.%s", cacheDir, hashPart, ext); return boostfmt("%s/%s.%s", cacheDir, hashPart, ext);
} }
ref<FSAccessor> RemoteFSAccessor::addToCache(std::string_view hashPart, std::string && nar) ref<FSAccessor> RemoteFSAccessor::addToCache(std::string_view hashPart, std::string && nar)

View file

@ -163,7 +163,7 @@ S3Helper::FileTransferResult S3Helper::getObject(
try { try {
auto result = checkAws(fmt("AWS error fetching '%s'", key), auto result = checkAws(boostfmt("AWS error fetching '%s'", key),
client->GetObject(request)); client->GetObject(request));
res.data = decompress(result.GetContentEncoding(), res.data = decompress(result.GetContentEncoding(),
@ -417,7 +417,7 @@ struct S3BinaryCacheStoreImpl : virtual S3BinaryCacheStoreConfig, public virtual
request.SetBody(istream); request.SetBody(istream);
auto result = checkAws(fmt("AWS error uploading '%s'", path), auto result = checkAws(boostfmt("AWS error uploading '%s'", path),
s3Helper.client->PutObject(request)); s3Helper.client->PutObject(request));
} }
@ -482,7 +482,7 @@ struct S3BinaryCacheStoreImpl : virtual S3BinaryCacheStoreConfig, public virtual
do { do {
debug("listing bucket 's3://%s' from key '%s'...", bucketName, marker); debug("listing bucket 's3://%s' from key '%s'...", bucketName, marker);
auto res = checkAws(fmt("AWS error listing bucket '%s'", bucketName), auto res = checkAws(boostfmt("AWS error listing bucket '%s'", bucketName),
s3Helper.client->ListObjects( s3Helper.client->ListObjects(
Aws::S3::Model::ListObjectsRequest() Aws::S3::Model::ListObjectsRequest()
.WithBucket(bucketName) .WithBucket(bucketName)

View file

@ -188,14 +188,14 @@ void SQLiteStmt::Use::exec()
int r = step(); int r = step();
assert(r != SQLITE_ROW); assert(r != SQLITE_ROW);
if (r != SQLITE_DONE) if (r != SQLITE_DONE)
SQLiteError::throw_(stmt.db, fmt("executing SQLite statement '%s'", sqlite3_expanded_sql(stmt.stmt))); SQLiteError::throw_(stmt.db, boostfmt("executing SQLite statement '%s'", sqlite3_expanded_sql(stmt.stmt)));
} }
bool SQLiteStmt::Use::next() bool SQLiteStmt::Use::next()
{ {
int r = step(); int r = step();
if (r != SQLITE_DONE && r != SQLITE_ROW) if (r != SQLITE_DONE && r != SQLITE_ROW)
SQLiteError::throw_(stmt.db, fmt("executing SQLite query '%s'", sqlite3_expanded_sql(stmt.stmt))); SQLiteError::throw_(stmt.db, boostfmt("executing SQLite query '%s'", sqlite3_expanded_sql(stmt.stmt)));
return r == SQLITE_ROW; return r == SQLITE_ROW;
} }

View file

@ -861,13 +861,13 @@ std::string Store::makeValidityRegistration(const StorePathSet & paths,
if (showHash) { if (showHash) {
s += info->narHash.to_string(Base16, false) + "\n"; s += info->narHash.to_string(Base16, false) + "\n";
s += fmt("%1%\n", info->narSize); s += boostfmt("%1%\n", info->narSize);
} }
auto deriver = showDerivers && info->deriver ? printStorePath(*info->deriver) : ""; auto deriver = showDerivers && info->deriver ? printStorePath(*info->deriver) : "";
s += deriver + "\n"; s += deriver + "\n";
s += fmt("%1%\n", info->references.size()); s += boostfmt("%1%\n", info->references.size());
for (auto & j : info->references) for (auto & j : info->references)
s += printStorePath(j) + "\n"; s += printStorePath(j) + "\n";
@ -1019,10 +1019,10 @@ static std::string makeCopyPathMessage(
std::string_view storePath) std::string_view storePath)
{ {
return srcUri == "local" || srcUri == "daemon" return srcUri == "local" || srcUri == "daemon"
? fmt("copying path '%s' to '%s'", storePath, dstUri) ? boostfmt("copying path '%s' to '%s'", storePath, dstUri)
: dstUri == "local" || dstUri == "daemon" : dstUri == "local" || dstUri == "daemon"
? fmt("copying path '%s' from '%s'", storePath, srcUri) ? boostfmt("copying path '%s' from '%s'", storePath, srcUri)
: fmt("copying path '%s' from '%s' to '%s'", storePath, srcUri, dstUri); : boostfmt("copying path '%s' from '%s' to '%s'", storePath, srcUri, dstUri);
} }
@ -1146,7 +1146,7 @@ std::map<StorePath, StorePath> copyPaths(
for (auto & path : storePaths) for (auto & path : storePaths)
if (!valid.count(path)) missing.insert(path); if (!valid.count(path)) missing.insert(path);
Activity act(*logger, lvlInfo, actCopyPaths, fmt("copying %d paths", missing.size())); Activity act(*logger, lvlInfo, actCopyPaths, boostfmt("copying %d paths", missing.size()));
// In the general case, `addMultipleToStore` requires a sorted list of // In the general case, `addMultipleToStore` requires a sorted list of
// store paths to add, so sort them right now // store paths to add, so sort them right now

View file

@ -93,7 +93,7 @@ static CgroupStats destroyCgroup(const Path & cgroup, bool returnStats)
throw Error("invalid pid '%s'", pid); throw Error("invalid pid '%s'", pid);
if (pidsShown.insert(pid).second) { if (pidsShown.insert(pid).second) {
try { try {
auto cmdline = readFile(fmt("/proc/%d/cmdline", pid)); auto cmdline = readFile(boostfmt("/proc/%d/cmdline", pid));
using namespace std::string_literals; using namespace std::string_literals;
warn("killing stray builder process %d (%s)...", warn("killing stray builder process %d (%s)...",
pid, trim(replaceStrings(cmdline, "\0"s, " "))); pid, trim(replaceStrings(cmdline, "\0"s, " ")));

View file

@ -83,7 +83,7 @@ void BaseSetting<T>::convertToArg(Args & args, const std::string & category)
{ {
args.addFlag({ args.addFlag({
.longName = name, .longName = name,
.description = fmt("Set the `%s` setting.", name), .description = boostfmt("Set the `%s` setting.", name),
.category = category, .category = category,
.labels = {"value"}, .labels = {"value"},
.handler = {[this](std::string s) { overridden = true; set(s); }}, .handler = {[this](std::string s) { overridden = true; set(s); }},
@ -93,7 +93,7 @@ void BaseSetting<T>::convertToArg(Args & args, const std::string & category)
if (isAppendable()) if (isAppendable())
args.addFlag({ args.addFlag({
.longName = "extra-" + name, .longName = "extra-" + name,
.description = fmt("Append to the `%s` setting.", name), .description = boostfmt("Append to the `%s` setting.", name),
.category = category, .category = category,
.labels = {"value"}, .labels = {"value"},
.handler = {[this](std::string s) { overridden = true; set(s, true); }}, .handler = {[this](std::string s) { overridden = true; set(s, true); }},

View file

@ -185,7 +185,7 @@ std::string Config::toKeyValue()
std::string res; std::string res;
for (const auto & s : _settings) for (const auto & s : _settings)
if (s.second.isAlias) if (s.second.isAlias)
res += fmt("%s = %s\n", s.first, s.second.setting->to_string()); res += boostfmt("%s = %s\n", s.first, s.second.setting->to_string());
return res; return res;
} }
@ -282,14 +282,14 @@ template<> void BaseSetting<bool>::convertToArg(Args & args, const std::string &
{ {
args.addFlag({ args.addFlag({
.longName = name, .longName = name,
.description = fmt("Enable the `%s` setting.", name), .description = boostfmt("Enable the `%s` setting.", name),
.category = category, .category = category,
.handler = {[this] { override(true); }}, .handler = {[this] { override(true); }},
.experimentalFeature = experimentalFeature, .experimentalFeature = experimentalFeature,
}); });
args.addFlag({ args.addFlag({
.longName = "no-" + name, .longName = "no-" + name,
.description = fmt("Disable the `%s` setting.", name), .description = boostfmt("Disable the `%s` setting.", name),
.category = category, .category = category,
.handler = {[this] { override(false); }}, .handler = {[this] { override(false); }},
.experimentalFeature = experimentalFeature, .experimentalFeature = experimentalFeature,
@ -504,7 +504,7 @@ std::string GlobalConfig::toKeyValue()
std::map<std::string, Config::SettingInfo> settings; std::map<std::string, Config::SettingInfo> settings;
globalConfig.getSettings(settings); globalConfig.getSettings(settings);
for (const auto & s : settings) for (const auto & s : settings)
res += fmt("%s = %s\n", s.first, s.second.value); res += boostfmt("%s = %s\n", s.first, s.second.value);
return res; return res;
} }

View file

@ -70,7 +70,7 @@ void printCodeLines(std::ostream & out,
// previous line of code. // previous line of code.
if (loc.prevLineOfCode.has_value()) { if (loc.prevLineOfCode.has_value()) {
out << std::endl out << std::endl
<< fmt("%1% %|2$5d|| %3%", << boostfmt("%1% %|2$5d|| %3%",
prefix, prefix,
(errPos.line - 1), (errPos.line - 1),
*loc.prevLineOfCode); *loc.prevLineOfCode);
@ -79,7 +79,7 @@ void printCodeLines(std::ostream & out,
if (loc.errLineOfCode.has_value()) { if (loc.errLineOfCode.has_value()) {
// line of code containing the error. // line of code containing the error.
out << std::endl out << std::endl
<< fmt("%1% %|2$5d|| %3%", << boostfmt("%1% %|2$5d|| %3%",
prefix, prefix,
(errPos.line), (errPos.line),
*loc.errLineOfCode); *loc.errLineOfCode);
@ -94,7 +94,7 @@ void printCodeLines(std::ostream & out,
std::string arrows("^"); std::string arrows("^");
out << std::endl out << std::endl
<< fmt("%1% |%2%" ANSI_RED "%3%" ANSI_NORMAL, << boostfmt("%1% |%2%" ANSI_RED "%3%" ANSI_NORMAL,
prefix, prefix,
spaces, spaces,
arrows); arrows);
@ -104,7 +104,7 @@ void printCodeLines(std::ostream & out,
// next line of code. // next line of code.
if (loc.nextLineOfCode.has_value()) { if (loc.nextLineOfCode.has_value()) {
out << std::endl out << std::endl
<< fmt("%1% %|2$5d|| %3%", << boostfmt("%1% %|2$5d|| %3%",
prefix, prefix,
(errPos.line + 1), (errPos.line + 1),
*loc.nextLineOfCode); *loc.nextLineOfCode);
@ -262,7 +262,7 @@ std::ostream & showErrorInfo(std::ostream & out, const ErrorInfo & einfo, bool s
// FIXME: show the program name as part of the trace? // FIXME: show the program name as part of the trace?
if (einfo.programName && einfo.programName != ErrorInfo::programName) if (einfo.programName && einfo.programName != ErrorInfo::programName)
prefix += fmt(" [%s]:" ANSI_NORMAL " ", einfo.programName.value_or("")); prefix += boostfmt(" [%s]:" ANSI_NORMAL " ", einfo.programName.value_or(""));
else else
prefix += ":" ANSI_NORMAL " "; prefix += ":" ANSI_NORMAL " ";

View file

@ -520,9 +520,9 @@ static Path tempName(Path tmpRoot, const Path & prefix, bool includePid,
{ {
tmpRoot = canonPath(tmpRoot.empty() ? defaultTempDir() : tmpRoot, true); tmpRoot = canonPath(tmpRoot.empty() ? defaultTempDir() : tmpRoot, true);
if (includePid) if (includePid)
return fmt("%1%/%2%-%3%-%4%", tmpRoot, prefix, getpid(), counter++); return boostfmt("%1%/%2%-%3%-%4%", tmpRoot, prefix, getpid(), counter++);
else else
return fmt("%1%/%2%-%3%", tmpRoot, prefix, counter++); return boostfmt("%1%/%2%-%3%", tmpRoot, prefix, counter++);
} }
Path createTempDir(const Path & tmpRoot, const Path & prefix, Path createTempDir(const Path & tmpRoot, const Path & prefix,
@ -577,7 +577,7 @@ void createSymlink(const Path & target, const Path & link)
void replaceSymlink(const Path & target, const Path & link) void replaceSymlink(const Path & target, const Path & link)
{ {
for (unsigned int n = 0; true; n++) { for (unsigned int n = 0; true; n++) {
Path tmp = canonPath(fmt("%s/.%d_%s", dirOf(link), n, baseNameOf(link))); Path tmp = canonPath(boostfmt("%s/.%d_%s", dirOf(link), n, baseNameOf(link)));
try { try {
createSymlink(target, tmp); createSymlink(target, tmp);

View file

@ -125,18 +125,18 @@ struct HintFmt
* And `stringFromUserInput` contains formatting placeholders like `%s`, then * And `stringFromUserInput` contains formatting placeholders like `%s`, then
* the code will crash at runtime. `fmt` helps you avoid this pitfall. * the code will crash at runtime. `fmt` helps you avoid this pitfall.
*/ */
inline std::string fmt(const std::string & s) inline std::string boostfmt(const std::string & s)
{ {
return s; return s;
} }
inline std::string fmt(const char * s) inline std::string boostfmt(const char * s)
{ {
return s; return s;
} }
template<typename... Args> template<typename... Args>
inline std::string fmt(const std::string & fs, const Args &... args) inline std::string boostfmt(const std::string & fs, const Args &... args)
{ {
boost::format f(fs); boost::format f(fs);
fmt_internal::setExceptions(f); fmt_internal::setExceptions(f);

View file

@ -153,7 +153,7 @@ public:
template<typename... Args> template<typename... Args>
inline void cout(const Args & ... args) inline void cout(const Args & ... args)
{ {
writeToStdout(fmt(args...)); writeToStdout(boostfmt(args...));
} }
virtual std::optional<char> ask(std::string_view s) virtual std::optional<char> ask(std::string_view s)
@ -262,7 +262,7 @@ extern Verbosity verbosity;
do { \ do { \
auto __lvl = level; \ auto __lvl = level; \
if (__lvl <= nix::verbosity) { \ if (__lvl <= nix::verbosity) { \
loggerParam->log(__lvl, fmt(args)); \ loggerParam->log(__lvl, boostfmt(args)); \
} \ } \
} while (0) } while (0)
#define printMsg(level, args...) printMsgUsing(logger, level, args) #define printMsg(level, args...) printMsgUsing(logger, level, args)

View file

@ -328,12 +328,12 @@ std::string statusToString(int status)
{ {
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
if (WIFEXITED(status)) if (WIFEXITED(status))
return fmt("failed with exit code %1%", WEXITSTATUS(status)); return boostfmt("failed with exit code %1%", WEXITSTATUS(status));
else if (WIFSIGNALED(status)) { else if (WIFSIGNALED(status)) {
int sig = WTERMSIG(status); int sig = WTERMSIG(status);
#if HAVE_STRSIGNAL #if HAVE_STRSIGNAL
const char * description = strsignal(sig); const char * description = strsignal(sig);
return fmt("failed due to signal %1% (%2%)", sig, description); return boostfmt("failed due to signal %1% (%2%)", sig, description);
#else #else
return fmt("failed due to signal %1%", sig); return fmt("failed due to signal %1%", sig);
#endif #endif

View file

@ -129,7 +129,7 @@ HashResult HashModuloSink::finish()
self-references already zeroed out do not produce a hash self-references already zeroed out do not produce a hash
collision. FIXME: proof. */ collision. FIXME: proof. */
for (auto & pos : rewritingSink.matches) for (auto & pos : rewritingSink.matches)
hashSink(fmt("|%d", pos)); hashSink(boostfmt("|%d", pos));
auto h = hashSink.finish(); auto h = hashSink.finish();
return {h.first, rewritingSink.pos}; return {h.first, rewritingSink.pos};

View file

@ -265,7 +265,7 @@ std::pair<std::string_view, std::string_view> getLine(std::string_view s)
std::string showBytes(uint64_t bytes) std::string showBytes(uint64_t bytes)
{ {
return fmt("%.2f MiB", bytes / (1024.0 * 1024.0)); return boostfmt("%.2f MiB", bytes / (1024.0 * 1024.0));
} }
} }

View file

@ -79,7 +79,7 @@ static void bindConnectProcHelper(
throw SysError("cannot %s to socket at '%s'", operationName, path); throw SysError("cannot %s to socket at '%s'", operationName, path);
writeFull(pipe.writeSide.get(), "0\n"); writeFull(pipe.writeSide.get(), "0\n");
} catch (SysError & e) { } catch (SysError & e) {
writeFull(pipe.writeSide.get(), fmt("%d\n", e.errNo)); writeFull(pipe.writeSide.get(), boostfmt("%d\n", e.errNo));
} catch (...) { } catch (...) {
writeFull(pipe.writeSide.get(), "-1\n"); writeFull(pipe.writeSide.get(), "-1\n");
} }

View file

@ -104,7 +104,7 @@ std::string percentEncode(std::string_view s, std::string_view keep)
|| keep.find(c) != std::string::npos) || keep.find(c) != std::string::npos)
res += c; res += c;
else else
res += fmt("%%%02X", (unsigned int) c); res += boostfmt("%%%02X", (unsigned int) c);
return res; return res;
} }

View file

@ -170,9 +170,9 @@ static void main_nix_build(int argc, char * * argv)
// read the shebang to understand which packages to read from. Since // read the shebang to understand which packages to read from. Since
// this is handled via nix-shell -p, we wrap our ruby script execution // this is handled via nix-shell -p, we wrap our ruby script execution
// in ruby -e 'load' which ignores the shebangs. // in ruby -e 'load' which ignores the shebangs.
envCommand = fmt("exec %1% %2% -e 'load(ARGV.shift)' -- %3% %4%", execArgs, interpreter, shellEscape(script), joined.str()); envCommand = boostfmt("exec %1% %2% -e 'load(ARGV.shift)' -- %3% %4%", execArgs, interpreter, shellEscape(script), joined.str());
} else { } else {
envCommand = fmt("exec %1% %2% %3% %4%", execArgs, interpreter, shellEscape(script), joined.str()); envCommand = boostfmt("exec %1% %2% %3% %4%", execArgs, interpreter, shellEscape(script), joined.str());
} }
} }
@ -488,7 +488,7 @@ static void main_nix_build(int argc, char * * argv)
environment variables and shell functions. Also don't environment variables and shell functions. Also don't
lose the current $PATH directories. */ lose the current $PATH directories. */
auto rcfile = (Path) tmpDir + "/rc"; auto rcfile = (Path) tmpDir + "/rc";
std::string rc = fmt( std::string rc = boostfmt(
R"(_nix_shell_clean_tmpdir() { command rm -rf %1%; }; )"s + R"(_nix_shell_clean_tmpdir() { command rm -rf %1%; }; )"s +
(keepTmp ? (keepTmp ?
"trap _nix_shell_clean_tmpdir EXIT; " "trap _nix_shell_clean_tmpdir EXIT; "
@ -589,7 +589,7 @@ static void main_nix_build(int argc, char * * argv)
auto & [counter, _wantedOutputs] = drvMap.at({drvPath}); auto & [counter, _wantedOutputs] = drvMap.at({drvPath});
std::string drvPrefix = outLink; std::string drvPrefix = outLink;
if (counter) if (counter)
drvPrefix += fmt("-%d", counter + 1); drvPrefix += boostfmt("-%d", counter + 1);
auto builtOutputs = store->queryPartialDerivationOutputMap(drvPath, &*evalStore); auto builtOutputs = store->queryPartialDerivationOutputMap(drvPath, &*evalStore);

View file

@ -136,7 +136,7 @@ static void getAllExprs(EvalState & state,
if (!seen.insert(attrName).second) { if (!seen.insert(attrName).second) {
std::string suggestionMessage = ""; std::string suggestionMessage = "";
if (path2.path.abs().find("channels") != std::string::npos && path.path.abs().find("channels") != std::string::npos) if (path2.path.abs().find("channels") != std::string::npos && path.path.abs().find("channels") != std::string::npos)
suggestionMessage = fmt("\nsuggestion: remove '%s' from either the root channels or the user channels", attrName); suggestionMessage = boostfmt("\nsuggestion: remove '%s' from either the root channels or the user channels", attrName);
printError("warning: name collision in input Nix expressions, skipping '%1%'" printError("warning: name collision in input Nix expressions, skipping '%1%'"
"%2%", path2, suggestionMessage); "%2%", path2, suggestionMessage);
continue; continue;
@ -357,7 +357,7 @@ static DrvInfos filterBySelector(EvalState & state, const DrvInfos & allElems,
} else { } else {
std::string suggestionMessage = ", maybe you meant:"; std::string suggestionMessage = ", maybe you meant:";
for (const auto & drvName : prefixHits) { for (const auto & drvName : prefixHits) {
suggestionMessage += fmt("\n%s", drvName); suggestionMessage += boostfmt("\n%s", drvName);
} }
throw Error("selector '%1%' matches no derivations" + suggestionMessage, selector.fullName); throw Error("selector '%1%' matches no derivations" + suggestionMessage, selector.fullName);
} }
@ -1237,11 +1237,11 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
xml.writeEmptyElement("meta", attrs2); xml.writeEmptyElement("meta", attrs2);
} else if (v->type() == nInt) { } else if (v->type() == nInt) {
attrs2["type"] = "int"; attrs2["type"] = "int";
attrs2["value"] = fmt("%1%", v->integer); attrs2["value"] = boostfmt("%1%", v->integer);
xml.writeEmptyElement("meta", attrs2); xml.writeEmptyElement("meta", attrs2);
} else if (v->type() == nFloat) { } else if (v->type() == nFloat) {
attrs2["type"] = "float"; attrs2["type"] = "float";
attrs2["value"] = fmt("%1%", v->fpoint); attrs2["value"] = boostfmt("%1%", v->fpoint);
xml.writeEmptyElement("meta", attrs2); xml.writeEmptyElement("meta", attrs2);
} else if (v->type() == nBool) { } else if (v->type() == nBool) {
attrs2["type"] = "bool"; attrs2["type"] = "bool";

View file

@ -81,7 +81,7 @@ void processExpr(EvalState & state, const Strings & attrPaths,
if (store2) if (store2)
drvPathS = store2->addPermRoot(drvPath, rootName); drvPathS = store2->addPermRoot(drvPath, rootName);
} }
std::cout << fmt("%s%s\n", drvPathS, (outputName != "out" ? "!" + outputName : "")); std::cout << boostfmt("%s%s\n", drvPathS, (outputName != "out" ? "!" + outputName : ""));
} }
} }
} }

View file

@ -27,7 +27,7 @@ static const std::string & nextColour()
static std::string makeEdge(std::string_view src, std::string_view dst) static std::string makeEdge(std::string_view src, std::string_view dst)
{ {
return fmt("%1% -> %2% [color = %3%];\n", return boostfmt("%1% -> %2% [color = %3%];\n",
dotQuote(src), dotQuote(dst), dotQuote(nextColour())); dotQuote(src), dotQuote(dst), dotQuote(nextColour()));
} }
@ -35,7 +35,7 @@ static std::string makeEdge(std::string_view src, std::string_view dst)
static std::string makeNode(std::string_view id, std::string_view label, static std::string makeNode(std::string_view id, std::string_view label,
std::string_view colour) std::string_view colour)
{ {
return fmt("%1% [label = %2%, shape = box, " return boostfmt("%1% [label = %2%, shape = box, "
"style = filled, fillcolor = %3%];\n", "style = filled, fillcolor = %3%];\n",
dotQuote(id), dotQuote(label), dotQuote(colour)); dotQuote(id), dotQuote(label), dotQuote(colour));
} }

View file

@ -26,14 +26,14 @@ static std::string symbolicName(std::string_view p)
static std::string makeEdge(std::string_view src, std::string_view dst) static std::string makeEdge(std::string_view src, std::string_view dst)
{ {
return fmt(" <edge source=\"%1%\" target=\"%2%\"/>\n", return boostfmt(" <edge source=\"%1%\" target=\"%2%\"/>\n",
xmlQuote(src), xmlQuote(dst)); xmlQuote(src), xmlQuote(dst));
} }
static std::string makeNode(const ValidPathInfo & info) static std::string makeNode(const ValidPathInfo & info)
{ {
return fmt( return boostfmt(
" <node id=\"%1%\">\n" " <node id=\"%1%\">\n"
" <data key=\"narSize\">%2%</data>\n" " <data key=\"narSize\">%2%</data>\n"
" <data key=\"name\">%3%</data>\n" " <data key=\"name\">%3%</data>\n"

View file

@ -164,7 +164,7 @@ static void opRealise(Strings opFlags, Strings opArgs)
auto paths2 = realisePath(i, false); auto paths2 = realisePath(i, false);
if (!noOutput) if (!noOutput)
for (auto & j : paths2) for (auto & j : paths2)
cout << fmt("%1%\n", j); cout << boostfmt("%1%\n", j);
} }
} }
@ -175,7 +175,7 @@ static void opAdd(Strings opFlags, Strings opArgs)
if (!opFlags.empty()) throw UsageError("unknown flag"); if (!opFlags.empty()) throw UsageError("unknown flag");
for (auto & i : opArgs) for (auto & i : opArgs)
cout << fmt("%s\n", store->printStorePath(store->addToStore(std::string(baseNameOf(i)), i))); cout << boostfmt("%s\n", store->printStorePath(store->addToStore(std::string(baseNameOf(i)), i)));
} }
@ -196,7 +196,7 @@ static void opAddFixed(Strings opFlags, Strings opArgs)
opArgs.pop_front(); opArgs.pop_front();
for (auto & i : opArgs) for (auto & i : opArgs)
std::cout << fmt("%s\n", store->printStorePath(store->addToStoreSlow(baseNameOf(i), i, method, hashAlgo).path)); std::cout << boostfmt("%s\n", store->printStorePath(store->addToStoreSlow(baseNameOf(i), i, method, hashAlgo).path));
} }
@ -217,7 +217,7 @@ static void opPrintFixedPath(Strings opFlags, Strings opArgs)
std::string hash = *i++; std::string hash = *i++;
std::string name = *i++; std::string name = *i++;
cout << fmt("%s\n", store->printStorePath(store->makeFixedOutputPath(name, FixedOutputInfo { cout << boostfmt("%s\n", store->printStorePath(store->makeFixedOutputPath(name, FixedOutputInfo {
.method = method, .method = method,
.hash = Hash::parseAny(hash, hashAlgo), .hash = Hash::parseAny(hash, hashAlgo),
.references = {}, .references = {},
@ -251,11 +251,11 @@ static void printTree(const StorePath & path,
const std::string & firstPad, const std::string & tailPad, StorePathSet & done) const std::string & firstPad, const std::string & tailPad, StorePathSet & done)
{ {
if (!done.insert(path).second) { if (!done.insert(path).second) {
cout << fmt("%s%s [...]\n", firstPad, store->printStorePath(path)); cout << boostfmt("%s%s [...]\n", firstPad, store->printStorePath(path));
return; return;
} }
cout << fmt("%s%s\n", firstPad, store->printStorePath(path)); cout << boostfmt("%s%s\n", firstPad, store->printStorePath(path));
auto info = store->queryPathInfo(path); auto info = store->queryPathInfo(path);
@ -330,7 +330,7 @@ static void opQuery(Strings opFlags, Strings opArgs)
for (auto & i : opArgs) { for (auto & i : opArgs) {
auto outputs = maybeUseOutputs(store->followLinksToStorePath(i), true, forceRealise); auto outputs = maybeUseOutputs(store->followLinksToStorePath(i), true, forceRealise);
for (auto & outputPath : outputs) for (auto & outputPath : outputs)
cout << fmt("%1%\n", store->printStorePath(outputPath)); cout << boostfmt("%1%\n", store->printStorePath(outputPath));
} }
break; break;
} }
@ -360,14 +360,14 @@ static void opQuery(Strings opFlags, Strings opArgs)
auto sorted = store->topoSortPaths(paths); auto sorted = store->topoSortPaths(paths);
for (StorePaths::reverse_iterator i = sorted.rbegin(); for (StorePaths::reverse_iterator i = sorted.rbegin();
i != sorted.rend(); ++i) i != sorted.rend(); ++i)
cout << fmt("%s\n", store->printStorePath(*i)); cout << boostfmt("%s\n", store->printStorePath(*i));
break; break;
} }
case qDeriver: case qDeriver:
for (auto & i : opArgs) { for (auto & i : opArgs) {
auto info = store->queryPathInfo(store->followLinksToStorePath(i)); auto info = store->queryPathInfo(store->followLinksToStorePath(i));
cout << fmt("%s\n", info->deriver ? store->printStorePath(*info->deriver) : "unknown-deriver"); cout << boostfmt("%s\n", info->deriver ? store->printStorePath(*info->deriver) : "unknown-deriver");
} }
break; break;
@ -382,7 +382,7 @@ static void opQuery(Strings opFlags, Strings opArgs)
auto sorted = store->topoSortPaths(result); auto sorted = store->topoSortPaths(result);
for (StorePaths::reverse_iterator i = sorted.rbegin(); for (StorePaths::reverse_iterator i = sorted.rbegin();
i != sorted.rend(); ++i) i != sorted.rend(); ++i)
cout << fmt("%s\n", store->printStorePath(*i)); cout << boostfmt("%s\n", store->printStorePath(*i));
break; break;
} }
@ -394,7 +394,7 @@ static void opQuery(Strings opFlags, Strings opArgs)
if (j == drv.env.end()) if (j == drv.env.end())
throw Error("derivation '%s' has no environment binding named '%s'", throw Error("derivation '%s' has no environment binding named '%s'",
store->printStorePath(path), bindingName); store->printStorePath(path), bindingName);
cout << fmt("%s\n", j->second); cout << boostfmt("%s\n", j->second);
} }
break; break;
@ -405,9 +405,9 @@ static void opQuery(Strings opFlags, Strings opArgs)
auto info = store->queryPathInfo(j); auto info = store->queryPathInfo(j);
if (query == qHash) { if (query == qHash) {
assert(info->narHash.type == htSHA256); assert(info->narHash.type == htSHA256);
cout << fmt("%s\n", info->narHash.to_string(Base32, true)); cout << boostfmt("%s\n", info->narHash.to_string(Base32, true));
} else if (query == qSize) } else if (query == qSize)
cout << fmt("%d\n", info->narSize); cout << boostfmt("%d\n", info->narSize);
} }
} }
break; break;
@ -439,7 +439,7 @@ static void opQuery(Strings opFlags, Strings opArgs)
case qResolve: { case qResolve: {
for (auto & i : opArgs) for (auto & i : opArgs)
cout << fmt("%s\n", store->printStorePath(store->followLinksToStorePath(i))); cout << boostfmt("%s\n", store->printStorePath(store->followLinksToStorePath(i)));
break; break;
} }
@ -458,7 +458,7 @@ static void opQuery(Strings opFlags, Strings opArgs)
for (auto & [target, links] : roots) for (auto & [target, links] : roots)
if (referrers.find(target) != referrers.end()) if (referrers.find(target) != referrers.end())
for (auto & link : links) for (auto & link : links)
cout << fmt("%1% -> %2%\n", link, gcStore.printStorePath(target)); cout << boostfmt("%1% -> %2%\n", link, gcStore.printStorePath(target));
break; break;
} }
@ -589,7 +589,7 @@ static void opCheckValidity(Strings opFlags, Strings opArgs)
auto path = store->followLinksToStorePath(i); auto path = store->followLinksToStorePath(i);
if (!store->isValidPath(path)) { if (!store->isValidPath(path)) {
if (printInvalid) if (printInvalid)
cout << fmt("%s\n", store->printStorePath(path)); cout << boostfmt("%s\n", store->printStorePath(path));
else else
throw Error("path '%s' is not valid", store->printStorePath(path)); throw Error("path '%s' is not valid", store->printStorePath(path));
} }
@ -714,7 +714,7 @@ static void opImport(Strings opFlags, Strings opArgs)
auto paths = store->importPaths(source, NoCheckSigs); auto paths = store->importPaths(source, NoCheckSigs);
for (auto & i : paths) for (auto & i : paths)
cout << fmt("%s\n", store->printStorePath(i)) << std::flush; cout << boostfmt("%s\n", store->printStorePath(i)) << std::flush;
} }

View file

@ -49,14 +49,14 @@ static void createOutLinks(const Path& outLink, const std::vector<BuiltPathWithR
std::visit(overloaded { std::visit(overloaded {
[&](const BuiltPath::Opaque & bo) { [&](const BuiltPath::Opaque & bo) {
std::string symlink = outLink; std::string symlink = outLink;
if (i) symlink += fmt("-%d", i); if (i) symlink += boostfmt("-%d", i);
store2.addPermRoot(bo.path, absPath(symlink)); store2.addPermRoot(bo.path, absPath(symlink));
}, },
[&](const BuiltPath::Built & bfd) { [&](const BuiltPath::Built & bfd) {
for (auto & output : bfd.outputs) { for (auto & output : bfd.outputs) {
std::string symlink = outLink; std::string symlink = outLink;
if (i) symlink += fmt("-%d", i); if (i) symlink += boostfmt("-%d", i);
if (output.first != "out") symlink += fmt("-%s", output.first); if (output.first != "out") symlink += boostfmt("-%s", output.first);
store2.addPermRoot(output.second, absPath(symlink)); store2.addPermRoot(output.second, absPath(symlink));
} }
}, },

View file

@ -18,7 +18,7 @@ struct CmdBundle : InstallableCommand
{ {
addFlag({ addFlag({
.longName = "bundler", .longName = "bundler",
.description = fmt("Use a custom bundler instead of the default (`%s`).", bundler), .description = boostfmt("Use a custom bundler instead of the default (`%s`).", bundler),
.labels = {"flake-url"}, .labels = {"flake-url"},
.handler = {&bundler}, .handler = {&bundler},
.completer = {[&](AddCompletions & completions, size_t, std::string_view prefix) { .completer = {[&](AddCompletions & completions, size_t, std::string_view prefix) {

View file

@ -145,9 +145,9 @@ struct BuildEnvironment
for (auto & [name, value] : vars) { for (auto & [name, value] : vars) {
if (!ignoreVars.count(name)) { if (!ignoreVars.count(name)) {
if (auto str = std::get_if<String>(&value)) { if (auto str = std::get_if<String>(&value)) {
out << fmt("%s=%s\n", name, shellEscape(str->value)); out << boostfmt("%s=%s\n", name, shellEscape(str->value));
if (str->exported) if (str->exported)
out << fmt("export %s\n", name); out << boostfmt("export %s\n", name);
} }
else if (auto arr = std::get_if<Array>(&value)) { else if (auto arr = std::get_if<Array>(&value)) {
out << "declare -a " << name << "=("; out << "declare -a " << name << "=(";
@ -337,18 +337,18 @@ struct Common : InstallableCommand, MixProfile
out << "unset shellHook\n"; out << "unset shellHook\n";
for (auto & var : savedVars) { for (auto & var : savedVars) {
out << fmt("%s=${%s:-}\n", var, var); out << boostfmt("%s=${%s:-}\n", var, var);
out << fmt("nix_saved_%s=\"$%s\"\n", var, var); out << boostfmt("nix_saved_%s=\"$%s\"\n", var, var);
} }
buildEnvironment.toBash(out, ignoreVars); buildEnvironment.toBash(out, ignoreVars);
for (auto & var : savedVars) for (auto & var : savedVars)
out << fmt("%s=\"$%s${nix_saved_%s:+:$nix_saved_%s}\"\n", var, var, var, var); out << boostfmt("%s=\"$%s${nix_saved_%s:+:$nix_saved_%s}\"\n", var, var, var, var);
out << "export NIX_BUILD_TOP=\"$(mktemp -d -t nix-shell.XXXXXX)\"\n"; out << "export NIX_BUILD_TOP=\"$(mktemp -d -t nix-shell.XXXXXX)\"\n";
for (auto & i : {"TMP", "TMPDIR", "TEMP", "TEMPDIR"}) for (auto & i : {"TMP", "TMPDIR", "TEMP", "TEMPDIR"})
out << fmt("export %s=\"$NIX_BUILD_TOP\"\n", i); out << boostfmt("export %s=\"$NIX_BUILD_TOP\"\n", i);
out << "eval \"${shellHook:-}\"\n"; out << "eval \"${shellHook:-}\"\n";
@ -564,34 +564,34 @@ struct CmdDevelop : Common, MixEnvironment
if (verbosity >= lvlDebug) if (verbosity >= lvlDebug)
script += "set -x\n"; script += "set -x\n";
script += fmt("command rm -f '%s'\n", rcFilePath); script += boostfmt("command rm -f '%s'\n", rcFilePath);
if (phase) { if (phase) {
if (!command.empty()) if (!command.empty())
throw UsageError("you cannot use both '--command' and '--phase'"); throw UsageError("you cannot use both '--command' and '--phase'");
// FIXME: foundMakefile is set by buildPhase, need to get // FIXME: foundMakefile is set by buildPhase, need to get
// rid of that. // rid of that.
script += fmt("foundMakefile=1\n"); script += boostfmt("foundMakefile=1\n");
script += fmt("runHook %1%Phase\n", *phase); script += boostfmt("runHook %1%Phase\n", *phase);
} }
else if (!command.empty()) { else if (!command.empty()) {
std::vector<std::string> args; std::vector<std::string> args;
for (auto s : command) for (auto s : command)
args.push_back(shellEscape(s)); args.push_back(shellEscape(s));
script += fmt("exec %s\n", concatStringsSep(" ", args)); script += boostfmt("exec %s\n", concatStringsSep(" ", args));
} }
else { else {
script = "[ -n \"$PS1\" ] && [ -e ~/.bashrc ] && source ~/.bashrc;\n" + script; script = "[ -n \"$PS1\" ] && [ -e ~/.bashrc ] && source ~/.bashrc;\n" + script;
if (developSettings.bashPrompt != "") if (developSettings.bashPrompt != "")
script += fmt("[ -n \"$PS1\" ] && PS1=%s;\n", script += boostfmt("[ -n \"$PS1\" ] && PS1=%s;\n",
shellEscape(developSettings.bashPrompt.get())); shellEscape(developSettings.bashPrompt.get()));
if (developSettings.bashPromptPrefix != "") if (developSettings.bashPromptPrefix != "")
script += fmt("[ -n \"$PS1\" ] && PS1=%s\"$PS1\";\n", script += boostfmt("[ -n \"$PS1\" ] && PS1=%s\"$PS1\";\n",
shellEscape(developSettings.bashPromptPrefix.get())); shellEscape(developSettings.bashPromptPrefix.get()));
if (developSettings.bashPromptSuffix != "") if (developSettings.bashPromptSuffix != "")
script += fmt("[ -n \"$PS1\" ] && PS1+=%s;\n", script += boostfmt("[ -n \"$PS1\" ] && PS1+=%s;\n",
shellEscape(developSettings.bashPromptSuffix.get())); shellEscape(developSettings.bashPromptSuffix.get()));
} }

View file

@ -95,9 +95,9 @@ void printClosureDiff(
if (showDelta || !removed.empty() || !added.empty()) { if (showDelta || !removed.empty() || !added.empty()) {
std::vector<std::string> items; std::vector<std::string> items;
if (!removed.empty() || !added.empty()) if (!removed.empty() || !added.empty())
items.push_back(fmt("%s → %s", showVersions(removed), showVersions(added))); items.push_back(boostfmt("%s → %s", showVersions(removed), showVersions(added)));
if (showDelta) if (showDelta)
items.push_back(fmt("%s%+.1f KiB" ANSI_NORMAL, sizeDelta > 0 ? ANSI_RED : ANSI_GREEN, sizeDelta / 1024.0)); items.push_back(boostfmt("%s%+.1f KiB" ANSI_NORMAL, sizeDelta > 0 ? ANSI_RED : ANSI_GREEN, sizeDelta / 1024.0));
logger->cout("%s%s: %s", indent, name, concatStringsSep(", ", items)); logger->cout("%s%s: %s", indent, name, concatStringsSep(", ", items));
} }
} }

View file

@ -17,7 +17,7 @@ std::string formatProtocol(unsigned int proto)
if (proto) { if (proto) {
auto major = GET_PROTOCOL_MAJOR(proto) >> 8; auto major = GET_PROTOCOL_MAJOR(proto) >> 8;
auto minor = GET_PROTOCOL_MINOR(proto); auto minor = GET_PROTOCOL_MINOR(proto);
return fmt("%1%.%2%", major, minor); return boostfmt("%1%.%2%", major, minor);
} }
return "unknown"; return "unknown";
} }
@ -147,7 +147,7 @@ struct CmdDoctor : StoreCommand
{ {
auto trustedMay = store->isTrustedClient(); auto trustedMay = store->isTrustedClient();
std::string_view trustedness = trustedMay ? (*trustedMay ? "trusted" : "not trusted") : "unknown trust"; std::string_view trustedness = trustedMay ? (*trustedMay ? "trusted" : "not trusted") : "unknown trust";
checkInfo(fmt("You are %s by store uri: %s", trustedness, store->getUri())); checkInfo(boostfmt("You are %s by store uri: %s", trustedness, store->getUri()));
} }
}; };

View file

@ -396,7 +396,7 @@ struct CmdFlakeCheck : FlakeCommand
auto checkDerivation = [&](const std::string & attrPath, Value & v, const PosIdx pos) -> std::optional<StorePath> { auto checkDerivation = [&](const std::string & attrPath, Value & v, const PosIdx pos) -> std::optional<StorePath> {
try { try {
Activity act(*logger, lvlInfo, actUnknown, Activity act(*logger, lvlInfo, actUnknown,
fmt("checking derivation %s", attrPath)); boostfmt("checking derivation %s", attrPath));
auto drvInfo = getDerivation(*state, v, false); auto drvInfo = getDerivation(*state, v, false);
if (!drvInfo) if (!drvInfo)
throw Error("flake attribute '%s' is not a derivation", attrPath); throw Error("flake attribute '%s' is not a derivation", attrPath);
@ -405,7 +405,7 @@ struct CmdFlakeCheck : FlakeCommand
auto storePath = drvInfo->queryDrvPath(); auto storePath = drvInfo->queryDrvPath();
if (storePath) { if (storePath) {
logger->log(lvlInfo, logger->log(lvlInfo,
fmt("derivation evaluated to %s", boostfmt("derivation evaluated to %s",
store->printStorePath(storePath.value()))); store->printStorePath(storePath.value())));
} }
return storePath; return storePath;
@ -438,7 +438,7 @@ struct CmdFlakeCheck : FlakeCommand
auto checkOverlay = [&](const std::string & attrPath, Value & v, const PosIdx pos) { auto checkOverlay = [&](const std::string & attrPath, Value & v, const PosIdx pos) {
try { try {
Activity act(*logger, lvlInfo, actUnknown, Activity act(*logger, lvlInfo, actUnknown,
fmt("checking overlay '%s'", attrPath)); boostfmt("checking overlay '%s'", attrPath));
state->forceValue(v, pos); state->forceValue(v, pos);
if (!v.isLambda()) { if (!v.isLambda()) {
throw Error("overlay is not a function, but %s instead", showType(v)); throw Error("overlay is not a function, but %s instead", showType(v));
@ -462,7 +462,7 @@ struct CmdFlakeCheck : FlakeCommand
auto checkModule = [&](const std::string & attrPath, Value & v, const PosIdx pos) { auto checkModule = [&](const std::string & attrPath, Value & v, const PosIdx pos) {
try { try {
Activity act(*logger, lvlInfo, actUnknown, Activity act(*logger, lvlInfo, actUnknown,
fmt("checking NixOS module '%s'", attrPath)); boostfmt("checking NixOS module '%s'", attrPath));
state->forceValue(v, pos); state->forceValue(v, pos);
} catch (Error & e) { } catch (Error & e) {
e.addTrace(resolve(pos), HintFmt("while checking the NixOS module '%s'", attrPath)); e.addTrace(resolve(pos), HintFmt("while checking the NixOS module '%s'", attrPath));
@ -475,7 +475,7 @@ struct CmdFlakeCheck : FlakeCommand
checkHydraJobs = [&](const std::string & attrPath, Value & v, const PosIdx pos) { checkHydraJobs = [&](const std::string & attrPath, Value & v, const PosIdx pos) {
try { try {
Activity act(*logger, lvlInfo, actUnknown, Activity act(*logger, lvlInfo, actUnknown,
fmt("checking Hydra job '%s'", attrPath)); boostfmt("checking Hydra job '%s'", attrPath));
state->forceAttrs(v, pos, ""); state->forceAttrs(v, pos, "");
if (state->isDerivation(v)) if (state->isDerivation(v))
@ -486,7 +486,7 @@ struct CmdFlakeCheck : FlakeCommand
auto attrPath2 = concatStrings(attrPath, ".", state->symbols[attr.name]); auto attrPath2 = concatStrings(attrPath, ".", state->symbols[attr.name]);
if (state->isDerivation(*attr.value)) { if (state->isDerivation(*attr.value)) {
Activity act(*logger, lvlInfo, actUnknown, Activity act(*logger, lvlInfo, actUnknown,
fmt("checking Hydra job '%s'", attrPath2)); boostfmt("checking Hydra job '%s'", attrPath2));
checkDerivation(attrPath2, *attr.value, attr.pos); checkDerivation(attrPath2, *attr.value, attr.pos);
} else } else
checkHydraJobs(attrPath2, *attr.value, attr.pos); checkHydraJobs(attrPath2, *attr.value, attr.pos);
@ -501,7 +501,7 @@ struct CmdFlakeCheck : FlakeCommand
auto checkNixOSConfiguration = [&](const std::string & attrPath, Value & v, const PosIdx pos) { auto checkNixOSConfiguration = [&](const std::string & attrPath, Value & v, const PosIdx pos) {
try { try {
Activity act(*logger, lvlInfo, actUnknown, Activity act(*logger, lvlInfo, actUnknown,
fmt("checking NixOS configuration '%s'", attrPath)); boostfmt("checking NixOS configuration '%s'", attrPath));
Bindings & bindings(*state->allocBindings(0)); Bindings & bindings(*state->allocBindings(0));
auto vToplevel = findAlongAttrPath(*state, "config.system.build.toplevel", bindings, v).first; auto vToplevel = findAlongAttrPath(*state, "config.system.build.toplevel", bindings, v).first;
state->forceValue(*vToplevel, pos); state->forceValue(*vToplevel, pos);
@ -516,7 +516,7 @@ struct CmdFlakeCheck : FlakeCommand
auto checkTemplate = [&](const std::string & attrPath, Value & v, const PosIdx pos) { auto checkTemplate = [&](const std::string & attrPath, Value & v, const PosIdx pos) {
try { try {
Activity act(*logger, lvlInfo, actUnknown, Activity act(*logger, lvlInfo, actUnknown,
fmt("checking template '%s'", attrPath)); boostfmt("checking template '%s'", attrPath));
state->forceAttrs(v, pos, ""); state->forceAttrs(v, pos, "");
@ -550,7 +550,7 @@ struct CmdFlakeCheck : FlakeCommand
auto checkBundler = [&](const std::string & attrPath, Value & v, const PosIdx pos) { auto checkBundler = [&](const std::string & attrPath, Value & v, const PosIdx pos) {
try { try {
Activity act(*logger, lvlInfo, actUnknown, Activity act(*logger, lvlInfo, actUnknown,
fmt("checking bundler '%s'", attrPath)); boostfmt("checking bundler '%s'", attrPath));
state->forceValue(v, pos); state->forceValue(v, pos);
if (!v.isLambda()) if (!v.isLambda())
throw Error("bundler must be a function"); throw Error("bundler must be a function");
@ -571,7 +571,7 @@ struct CmdFlakeCheck : FlakeCommand
*vFlake, *vFlake,
[&](const std::string & name, Value & vOutput, const PosIdx pos) { [&](const std::string & name, Value & vOutput, const PosIdx pos) {
Activity act(*logger, lvlInfo, actUnknown, Activity act(*logger, lvlInfo, actUnknown,
fmt("checking flake output '%s'", name)); boostfmt("checking flake output '%s'", name));
try { try {
evalSettings.enableImportFromDerivation.setDefault(name != "hydraJobs"); evalSettings.enableImportFromDerivation.setDefault(name != "hydraJobs");
@ -599,7 +599,7 @@ struct CmdFlakeCheck : FlakeCommand
state->forceAttrs(*attr.value, attr.pos, ""); state->forceAttrs(*attr.value, attr.pos, "");
for (auto & attr2 : *attr.value->attrs) { for (auto & attr2 : *attr.value->attrs) {
auto drvPath = checkDerivation( auto drvPath = checkDerivation(
fmt("%s.%s.%s", name, attr_name, state->symbols[attr2.name]), boostfmt("%s.%s.%s", name, attr_name, state->symbols[attr2.name]),
*attr2.value, attr2.pos); *attr2.value, attr2.pos);
if (drvPath && attr_name == settings.thisSystem.get()) { if (drvPath && attr_name == settings.thisSystem.get()) {
drvPaths.push_back(DerivedPath::Built { drvPaths.push_back(DerivedPath::Built {
@ -619,7 +619,7 @@ struct CmdFlakeCheck : FlakeCommand
checkSystemName(attr_name, attr.pos); checkSystemName(attr_name, attr.pos);
if (checkSystemType(attr_name, attr.pos)) { if (checkSystemType(attr_name, attr.pos)) {
checkApp( checkApp(
fmt("%s.%s", name, attr_name), boostfmt("%s.%s", name, attr_name),
*attr.value, attr.pos); *attr.value, attr.pos);
}; };
} }
@ -634,7 +634,7 @@ struct CmdFlakeCheck : FlakeCommand
state->forceAttrs(*attr.value, attr.pos, ""); state->forceAttrs(*attr.value, attr.pos, "");
for (auto & attr2 : *attr.value->attrs) for (auto & attr2 : *attr.value->attrs)
checkDerivation( checkDerivation(
fmt("%s.%s.%s", name, attr_name, state->symbols[attr2.name]), boostfmt("%s.%s.%s", name, attr_name, state->symbols[attr2.name]),
*attr2.value, attr2.pos); *attr2.value, attr2.pos);
}; };
} }
@ -649,7 +649,7 @@ struct CmdFlakeCheck : FlakeCommand
state->forceAttrs(*attr.value, attr.pos, ""); state->forceAttrs(*attr.value, attr.pos, "");
for (auto & attr2 : *attr.value->attrs) for (auto & attr2 : *attr.value->attrs)
checkApp( checkApp(
fmt("%s.%s.%s", name, attr_name, state->symbols[attr2.name]), boostfmt("%s.%s.%s", name, attr_name, state->symbols[attr2.name]),
*attr2.value, attr2.pos); *attr2.value, attr2.pos);
}; };
} }
@ -662,7 +662,7 @@ struct CmdFlakeCheck : FlakeCommand
checkSystemName(attr_name, attr.pos); checkSystemName(attr_name, attr.pos);
if (checkSystemType(attr_name, attr.pos)) { if (checkSystemType(attr_name, attr.pos)) {
checkDerivation( checkDerivation(
fmt("%s.%s", name, attr_name), boostfmt("%s.%s", name, attr_name),
*attr.value, attr.pos); *attr.value, attr.pos);
}; };
} }
@ -675,7 +675,7 @@ struct CmdFlakeCheck : FlakeCommand
checkSystemName(attr_name, attr.pos); checkSystemName(attr_name, attr.pos);
if (checkSystemType(attr_name, attr.pos) ) { if (checkSystemType(attr_name, attr.pos) ) {
checkApp( checkApp(
fmt("%s.%s", name, attr_name), boostfmt("%s.%s", name, attr_name),
*attr.value, attr.pos); *attr.value, attr.pos);
}; };
} }
@ -696,7 +696,7 @@ struct CmdFlakeCheck : FlakeCommand
else if (name == "overlays") { else if (name == "overlays") {
state->forceAttrs(vOutput, pos, ""); state->forceAttrs(vOutput, pos, "");
for (auto & attr : *vOutput.attrs) for (auto & attr : *vOutput.attrs)
checkOverlay(fmt("%s.%s", name, state->symbols[attr.name]), checkOverlay(boostfmt("%s.%s", name, state->symbols[attr.name]),
*attr.value, attr.pos); *attr.value, attr.pos);
} }
@ -706,14 +706,14 @@ struct CmdFlakeCheck : FlakeCommand
else if (name == "nixosModules") { else if (name == "nixosModules") {
state->forceAttrs(vOutput, pos, ""); state->forceAttrs(vOutput, pos, "");
for (auto & attr : *vOutput.attrs) for (auto & attr : *vOutput.attrs)
checkModule(fmt("%s.%s", name, state->symbols[attr.name]), checkModule(boostfmt("%s.%s", name, state->symbols[attr.name]),
*attr.value, attr.pos); *attr.value, attr.pos);
} }
else if (name == "nixosConfigurations") { else if (name == "nixosConfigurations") {
state->forceAttrs(vOutput, pos, ""); state->forceAttrs(vOutput, pos, "");
for (auto & attr : *vOutput.attrs) for (auto & attr : *vOutput.attrs)
checkNixOSConfiguration(fmt("%s.%s", name, state->symbols[attr.name]), checkNixOSConfiguration(boostfmt("%s.%s", name, state->symbols[attr.name]),
*attr.value, attr.pos); *attr.value, attr.pos);
} }
@ -726,7 +726,7 @@ struct CmdFlakeCheck : FlakeCommand
else if (name == "templates") { else if (name == "templates") {
state->forceAttrs(vOutput, pos, ""); state->forceAttrs(vOutput, pos, "");
for (auto & attr : *vOutput.attrs) for (auto & attr : *vOutput.attrs)
checkTemplate(fmt("%s.%s", name, state->symbols[attr.name]), checkTemplate(boostfmt("%s.%s", name, state->symbols[attr.name]),
*attr.value, attr.pos); *attr.value, attr.pos);
} }
@ -737,7 +737,7 @@ struct CmdFlakeCheck : FlakeCommand
checkSystemName(attr_name, attr.pos); checkSystemName(attr_name, attr.pos);
if (checkSystemType(attr_name, attr.pos)) { if (checkSystemType(attr_name, attr.pos)) {
checkBundler( checkBundler(
fmt("%s.%s", name, attr_name), boostfmt("%s.%s", name, attr_name),
*attr.value, attr.pos); *attr.value, attr.pos);
}; };
} }
@ -752,7 +752,7 @@ struct CmdFlakeCheck : FlakeCommand
state->forceAttrs(*attr.value, attr.pos, ""); state->forceAttrs(*attr.value, attr.pos, "");
for (auto & attr2 : *attr.value->attrs) { for (auto & attr2 : *attr.value->attrs) {
checkBundler( checkBundler(
fmt("%s.%s.%s", name, attr_name, state->symbols[attr2.name]), boostfmt("%s.%s.%s", name, attr_name, state->symbols[attr2.name]),
*attr2.value, attr2.pos); *attr2.value, attr2.pos);
} }
}; };
@ -784,7 +784,7 @@ struct CmdFlakeCheck : FlakeCommand
if (build && !drvPaths.empty()) { if (build && !drvPaths.empty()) {
Activity act(*logger, lvlInfo, actUnknown, Activity act(*logger, lvlInfo, actUnknown,
fmt("running %d flake checks", drvPaths.size())); boostfmt("running %d flake checks", drvPaths.size()));
store->buildPaths(drvPaths); store->buildPaths(drvPaths);
} }
if (hasErrors) if (hasErrors)
@ -1196,7 +1196,7 @@ struct CmdFlakeShow : FlakeCommand, MixJSON
auto attrPathS = state->symbols.resolve(attrPath); auto attrPathS = state->symbols.resolve(attrPath);
Activity act(*logger, lvlInfo, actUnknown, Activity act(*logger, lvlInfo, actUnknown,
fmt("evaluating '%s'", concatStringsSep(".", attrPathS))); boostfmt("evaluating '%s'", concatStringsSep(".", attrPathS)));
try { try {
auto recurse = [&]() auto recurse = [&]()
@ -1216,7 +1216,7 @@ struct CmdFlakeShow : FlakeCommand, MixJSON
auto attrPath2(attrPath); auto attrPath2(attrPath);
attrPath2.push_back(attr); attrPath2.push_back(attr);
auto j2 = visit(*visitor2, attrPath2, auto j2 = visit(*visitor2, attrPath2,
fmt(ANSI_GREEN "%s%s" ANSI_NORMAL ANSI_BOLD "%s" ANSI_NORMAL, nextPrefix, last ? treeLast : treeConn, attrName), boostfmt(ANSI_GREEN "%s%s" ANSI_NORMAL ANSI_BOLD "%s" ANSI_NORMAL, nextPrefix, last ? treeLast : treeConn, attrName),
nextPrefix + (last ? treeNull : treeLine)); nextPrefix + (last ? treeNull : treeLine));
if (json) j.emplace(attrName, std::move(j2)); if (json) j.emplace(attrName, std::move(j2));
} }
@ -1274,9 +1274,9 @@ struct CmdFlakeShow : FlakeCommand, MixJSON
{ {
if (!showAllSystems && std::string(attrPathS[1]) != localSystem) { if (!showAllSystems && std::string(attrPathS[1]) != localSystem) {
if (!json) if (!json)
logger->cout(fmt("%s " ANSI_WARNING "omitted" ANSI_NORMAL " (use '--all-systems' to show)", headerPrefix)); logger->cout(boostfmt("%s " ANSI_WARNING "omitted" ANSI_NORMAL " (use '--all-systems' to show)", headerPrefix));
else { else {
logger->warn(fmt("%s omitted (use '--all-systems' to show)", concatStringsSep(".", attrPathS))); logger->warn(boostfmt("%s omitted (use '--all-systems' to show)", concatStringsSep(".", attrPathS)));
} }
} else { } else {
if (visitor.isDerivation()) if (visitor.isDerivation())
@ -1298,15 +1298,15 @@ struct CmdFlakeShow : FlakeCommand, MixJSON
recurse(); recurse();
else if (!showLegacy){ else if (!showLegacy){
if (!json) if (!json)
logger->cout(fmt("%s " ANSI_WARNING "omitted" ANSI_NORMAL " (use '--legacy' to show)", headerPrefix)); logger->cout(boostfmt("%s " ANSI_WARNING "omitted" ANSI_NORMAL " (use '--legacy' to show)", headerPrefix));
else { else {
logger->warn(fmt("%s omitted (use '--legacy' to show)", concatStringsSep(".", attrPathS))); logger->warn(boostfmt("%s omitted (use '--legacy' to show)", concatStringsSep(".", attrPathS)));
} }
} else if (!showAllSystems && std::string(attrPathS[1]) != localSystem) { } else if (!showAllSystems && std::string(attrPathS[1]) != localSystem) {
if (!json) if (!json)
logger->cout(fmt("%s " ANSI_WARNING "omitted" ANSI_NORMAL " (use '--all-systems' to show)", headerPrefix)); logger->cout(boostfmt("%s " ANSI_WARNING "omitted" ANSI_NORMAL " (use '--all-systems' to show)", headerPrefix));
else { else {
logger->warn(fmt("%s omitted (use '--all-systems' to show)", concatStringsSep(".", attrPathS))); logger->warn(boostfmt("%s omitted (use '--all-systems' to show)", concatStringsSep(".", attrPathS)));
} }
} else { } else {
if (visitor.isDerivation()) if (visitor.isDerivation())
@ -1368,7 +1368,7 @@ struct CmdFlakeShow : FlakeCommand, MixJSON
auto cache = openEvalCache(*state, flake); auto cache = openEvalCache(*state, flake);
auto j = visit(*cache->getRoot(), {}, fmt(ANSI_BOLD "%s" ANSI_NORMAL, flake->flake.lockedRef), ""); auto j = visit(*cache->getRoot(), {}, boostfmt(ANSI_BOLD "%s" ANSI_NORMAL, flake->flake.lockedRef), "");
if (json) if (json)
logger->cout("%s", j.dump()); logger->cout("%s", j.dump());
} }

View file

@ -113,7 +113,7 @@ struct CmdToBase : Command
std::string description() override std::string description() override
{ {
return fmt("convert a hash to %s representation", return boostfmt("convert a hash to %s representation",
base == Base16 ? "base-16" : base == Base16 ? "base-16" :
base == Base32 ? "base-32" : base == Base32 ? "base-32" :
base == Base64 ? "base-64" : base == Base64 ? "base-64" :

View file

@ -51,7 +51,7 @@ struct MixLs : virtual Args, MixJSON
(st.isExecutable ? "-r-xr-xr-x" : "-r--r--r--") : (st.isExecutable ? "-r-xr-xr-x" : "-r--r--r--") :
st.type == FSAccessor::Type::tSymlink ? "lrwxrwxrwx" : st.type == FSAccessor::Type::tSymlink ? "lrwxrwxrwx" :
"dr-xr-xr-x"; "dr-xr-xr-x";
auto line = fmt("%s %20d %s", tp, st.fileSize, relPath); auto line = boostfmt("%s %20d %s", tp, st.fileSize, relPath);
if (st.type == FSAccessor::Type::tSymlink) if (st.type == FSAccessor::Type::tSymlink)
line += " -> " + accessor->readLink(curPath); line += " -> " + accessor->readLink(curPath);
logger->cout(line); logger->cout(line);

View file

@ -220,7 +220,7 @@ struct NixArgs : virtual MultiCommand, virtual MixCommonArgs, virtual RootArgs
lowdown. */ lowdown. */
static void showHelp(std::vector<std::string> subcommand, NixArgs & toplevel) static void showHelp(std::vector<std::string> subcommand, NixArgs & toplevel)
{ {
auto mdName = subcommand.empty() ? "nix" : fmt("nix3-%s", concatStringsSep("-", subcommand)); auto mdName = subcommand.empty() ? "nix" : boostfmt("nix3-%s", concatStringsSep("-", subcommand));
evalSettings.restrictEval = false; evalSettings.restrictEval = false;
evalSettings.pureEval = false; evalSettings.pureEval = false;

View file

@ -64,7 +64,7 @@ struct CmdPathInfo : StorePathsCommand, MixJSON
void printSize(uint64_t value) void printSize(uint64_t value)
{ {
if (!humanReadable) { if (!humanReadable) {
std::cout << fmt("\t%11d", value); std::cout << boostfmt("\t%11d", value);
return; return;
} }
@ -77,7 +77,7 @@ struct CmdPathInfo : StorePathsCommand, MixJSON
++power; ++power;
res /= 1024; res /= 1024;
} }
std::cout << fmt("\t%6.1f%c", res, idents.at(power)); std::cout << boostfmt("\t%6.1f%c", res, idents.at(power));
} }
void run(ref<Store> store, StorePaths && storePaths) override void run(ref<Store> store, StorePaths && storePaths) override

View file

@ -104,7 +104,7 @@ std::tuple<StorePath, Hash> prefetchFile(
/* Optionally unpack the file. */ /* Optionally unpack the file. */
if (unpack) { if (unpack) {
Activity act(*logger, lvlChatty, actUnknown, Activity act(*logger, lvlChatty, actUnknown,
fmt("unpacking '%s'", url)); boostfmt("unpacking '%s'", url));
Path unpacked = (Path) tmpDir + "/unpacked"; Path unpacked = (Path) tmpDir + "/unpacked";
createDirs(unpacked); createDirs(unpacked);
unpackTarfile(tmpFile, unpacked); unpackTarfile(tmpFile, unpacked);
@ -119,7 +119,7 @@ std::tuple<StorePath, Hash> prefetchFile(
} }
Activity act(*logger, lvlChatty, actUnknown, Activity act(*logger, lvlChatty, actUnknown,
fmt("adding '%s' to the store", url)); boostfmt("adding '%s' to the store", url));
auto info = store->addToStoreSlow(*name, tmpFile, ingestionMethod, hashType, expectedHash); auto info = store->addToStoreSlow(*name, tmpFile, ingestionMethod, hashType, expectedHash);
storePath = info.path; storePath = info.path;

View file

@ -328,7 +328,7 @@ struct CmdProfileUpgrade : virtual SourceExprCommand, MixDefaultProfile, MixProf
*logger, *logger,
lvlChatty, lvlChatty,
actUnknown, actUnknown,
fmt("checking '%s' for updates", element.source->attrPath), boostfmt("checking '%s' for updates", element.source->attrPath),
Logger::Fields{element.source->attrPath} Logger::Fields{element.source->attrPath}
); );
@ -518,7 +518,7 @@ struct CmdProfileHistory : virtual StoreCommand, EvalCommand, MixDefaultProfile
gen.number == curGen ? ANSI_GREEN : ANSI_BOLD, gen.number == curGen ? ANSI_GREEN : ANSI_BOLD,
gen.number, gen.number,
std::put_time(std::gmtime(&gen.creationTime), "%Y-%m-%d"), std::put_time(std::gmtime(&gen.creationTime), "%Y-%m-%d"),
prevGen ? fmt(" <- %d", prevGen->first.number) : ""); prevGen ? boostfmt(" <- %d", prevGen->first.number) : "");
ProfileManifest::printDiff( ProfileManifest::printDiff(
prevGen ? prevGen->second : ProfileManifest(), prevGen ? prevGen->second : ProfileManifest(),

View file

@ -275,8 +275,8 @@ void chrootHelper(int argc, char * * argv)
throw SysError("mounting '%s' on '%s'", realStoreDir, storeDir); throw SysError("mounting '%s' on '%s'", realStoreDir, storeDir);
writeFile("/proc/self/setgroups", "deny"); writeFile("/proc/self/setgroups", "deny");
writeFile("/proc/self/uid_map", fmt("%d %d %d", uid, uid, 1)); writeFile("/proc/self/uid_map", boostfmt("%d %d %d", uid, uid, 1));
writeFile("/proc/self/gid_map", fmt("%d %d %d", gid, gid, 1)); writeFile("/proc/self/gid_map", boostfmt("%d %d %d", gid, gid, 1));
if (system != "") if (system != "")
setPersonality(system); setPersonality(system);

View file

@ -98,7 +98,7 @@ struct CmdSearch : InstallableCommand, MixJSON
auto attrPathS = state->symbols.resolve(attrPath); auto attrPathS = state->symbols.resolve(attrPath);
Activity act(*logger, lvlInfo, actUnknown, Activity act(*logger, lvlInfo, actUnknown,
fmt("evaluating '%s'", concatStringsSep(".", attrPathS))); boostfmt("evaluating '%s'", concatStringsSep(".", attrPathS)));
try { try {
auto recurse = [&]() auto recurse = [&]()
{ {

View file

@ -93,12 +93,12 @@ struct CmdUpgradeNix : MixDryRun, EvalCommand
} }
{ {
Activity act(*logger, lvlInfo, actUnknown, fmt("downloading '%s'...", store->printStorePath(storePath))); Activity act(*logger, lvlInfo, actUnknown, boostfmt("downloading '%s'...", store->printStorePath(storePath)));
store->ensurePath(storePath); store->ensurePath(storePath);
} }
{ {
Activity act(*logger, lvlInfo, actUnknown, fmt("verifying that '%s' works...", store->printStorePath(storePath))); Activity act(*logger, lvlInfo, actUnknown, boostfmt("verifying that '%s' works...", store->printStorePath(storePath)));
auto program = store->printStorePath(storePath) + "/bin/nix-env"; auto program = store->printStorePath(storePath) + "/bin/nix-env";
auto s = runProgram(program, false, {"--version"}); auto s = runProgram(program, false, {"--version"});
if (s.find("Nix") == std::string::npos) if (s.find("Nix") == std::string::npos)

View file

@ -94,7 +94,7 @@ struct CmdVerify : StorePathsCommand
// Note: info->path can be different from storePath // Note: info->path can be different from storePath
// for binary cache stores when using --all (since we // for binary cache stores when using --all (since we
// can't enumerate names efficiently). // can't enumerate names efficiently).
Activity act2(*logger, lvlInfo, actUnknown, fmt("checking '%s'", store->printStorePath(info->path))); Activity act2(*logger, lvlInfo, actUnknown, boostfmt("checking '%s'", store->printStorePath(info->path)));
if (!noContents) { if (!noContents) {

View file

@ -234,7 +234,7 @@ struct CmdWhyDepends : SourceExprCommand, MixOperateOnOptions
if (pos != std::string::npos) { if (pos != std::string::npos) {
size_t margin = 32; size_t margin = 32;
auto pos2 = pos >= margin ? pos - margin : 0; auto pos2 = pos >= margin ? pos - margin : 0;
hits[hash].emplace_back(fmt("%s: …%s…", hits[hash].emplace_back(boostfmt("%s: …%s…",
p2, p2,
hilite(filterPrintable( hilite(filterPrintable(
std::string(contents, pos2, pos - pos2 + hash.size() + margin)), std::string(contents, pos2, pos - pos2 + hash.size() + margin)),
@ -250,7 +250,7 @@ struct CmdWhyDepends : SourceExprCommand, MixOperateOnOptions
for (auto & hash : hashes) { for (auto & hash : hashes) {
auto pos = target.find(hash); auto pos = target.find(hash);
if (pos != std::string::npos) if (pos != std::string::npos)
hits[hash].emplace_back(fmt("%s -> %s", p2, hits[hash].emplace_back(boostfmt("%s -> %s", p2,
hilite(target, pos, StorePath::HashLen, getColour(hash)))); hilite(target, pos, StorePath::HashLen, getColour(hash))));
} }
} }

View file

@ -157,9 +157,9 @@ int main(int argc, char ** argv)
uname(&_uname); uname(&_uname);
auto cacheParentDir = fmt("%1%/dependency-maps", settings.nixStateDir); auto cacheParentDir = boostfmt("%1%/dependency-maps", settings.nixStateDir);
cacheDir = fmt("%1%/%2%-%3%-%4%", cacheParentDir, _uname.machine, _uname.sysname, _uname.release); cacheDir = boostfmt("%1%/%2%-%3%-%4%", cacheParentDir, _uname.machine, _uname.sysname, _uname.release);
mkdir(cacheParentDir.c_str(), 0755); mkdir(cacheParentDir.c_str(), 0755);
mkdir(cacheDir.c_str(), 0755); mkdir(cacheDir.c_str(), 0755);

View file

@ -25,7 +25,7 @@ TEST(Arguments, lookupFileArg) {
// Meson should be allowed to pass us a relative path here tbh. // Meson should be allowed to pass us a relative path here tbh.
auto const canonDataPath = CanonPath::fromCwd(unitDataPath); auto const canonDataPath = CanonPath::fromCwd(unitDataPath);
std::string const searchPathElem = fmt("example=%s", unitDataPath); std::string const searchPathElem = boostfmt("example=%s", unitDataPath);
SearchPath searchPath; SearchPath searchPath;
searchPath.elements.push_back(SearchPath::Elem::parse(searchPathElem)); searchPath.elements.push_back(SearchPath::Elem::parse(searchPathElem));

View file

@ -66,21 +66,21 @@ namespace nix {
return arg.type() == nAttrs; return arg.type() == nAttrs;
} }
MATCHER_P(IsStringEq, s, fmt("The string is equal to \"%1%\"", s)) { MATCHER_P(IsStringEq, s, boostfmt("The string is equal to \"%1%\"", s)) {
if (arg.type() != nString) { if (arg.type() != nString) {
return false; return false;
} }
return std::string_view(arg.string.s) == std::string_view(s); return std::string_view(arg.string.s) == std::string_view(s);
} }
MATCHER_P(IsIntEq, v, fmt("The string is equal to \"%1%\"", v)) { MATCHER_P(IsIntEq, v, boostfmt("The string is equal to \"%1%\"", v)) {
if (arg.type() != nInt) { if (arg.type() != nInt) {
return false; return false;
} }
return arg.integer == v; return arg.integer == v;
} }
MATCHER_P(IsFloatEq, v, fmt("The float is equal to \"%1%\"", v)) { MATCHER_P(IsFloatEq, v, boostfmt("The float is equal to \"%1%\"", v)) {
if (arg.type() != nFloat) { if (arg.type() != nFloat) {
return false; return false;
} }
@ -101,7 +101,7 @@ namespace nix {
return arg.boolean == false; return arg.boolean == false;
} }
MATCHER_P(IsPathEq, p, fmt("Is a path equal to \"%1%\"", p)) { MATCHER_P(IsPathEq, p, boostfmt("Is a path equal to \"%1%\"", p)) {
if (arg.type() != nPath) { if (arg.type() != nPath) {
*result_listener << "Expected a path got " << arg.type(); *result_listener << "Expected a path got " << arg.type();
return false; return false;
@ -113,7 +113,7 @@ namespace nix {
} }
MATCHER_P(IsListOfSize, n, fmt("Is a list of size [%1%]", n)) { MATCHER_P(IsListOfSize, n, boostfmt("Is a list of size [%1%]", n)) {
if (arg.type() != nList) { if (arg.type() != nList) {
*result_listener << "Expected list got " << arg.type(); *result_listener << "Expected list got " << arg.type();
return false; return false;
@ -124,7 +124,7 @@ namespace nix {
return true; return true;
} }
MATCHER_P(IsAttrsOfSize, n, fmt("Is a set of size [%1%]", n)) { MATCHER_P(IsAttrsOfSize, n, boostfmt("Is a set of size [%1%]", n)) {
if (arg.type() != nAttrs) { if (arg.type() != nAttrs) {
*result_listener << "Expected set got " << arg.type(); *result_listener << "Expected set got " << arg.type();
return false; return false;

View file

@ -687,7 +687,7 @@ namespace nix {
TEST_P(ParseDrvNamePrimOpTest, parseDrvName) { TEST_P(ParseDrvNamePrimOpTest, parseDrvName) {
auto [input, expectedName, expectedVersion] = GetParam(); auto [input, expectedName, expectedVersion] = GetParam();
const auto expr = fmt("builtins.parseDrvName \"%1%\"", input); const auto expr = boostfmt("builtins.parseDrvName \"%1%\"", input);
auto v = eval(expr); auto v = eval(expr);
ASSERT_THAT(v, IsAttrsOfSize(2)); ASSERT_THAT(v, IsAttrsOfSize(2));

View file

@ -32,7 +32,7 @@ namespace nix
progressBar, progressBar,
lvlDebug, lvlDebug,
actFileTransfer, actFileTransfer,
fmt("downloading '%s'", TEST_URL), boostfmt("downloading '%s'", TEST_URL),
{ "https://github.com/NixOS/nixpkgs/archive/master.tar.gz" } { "https://github.com/NixOS/nixpkgs/archive/master.tar.gz" }
); );
act.progress(TEST_DONE, TEST_EXPECTED); act.progress(TEST_DONE, TEST_EXPECTED);

View file

@ -156,7 +156,7 @@ TEST(FileTransfer, NOT_ON_DARWIN(reportsSetupErrors))
auto [port, srv] = serveHTTP("404 not found", "", [] { return ""; }); auto [port, srv] = serveHTTP("404 not found", "", [] { return ""; });
auto ft = makeFileTransfer(); auto ft = makeFileTransfer();
ASSERT_THROW( ASSERT_THROW(
ft->transfer(FileTransferRequest(fmt("http://[::1]:%d/index", port))), ft->transfer(FileTransferRequest(boostfmt("http://[::1]:%d/index", port))),
FileTransferError); FileTransferError);
} }
@ -171,7 +171,7 @@ TEST(FileTransfer, NOT_ON_DARWIN(defersFailures))
return std::string(1024 * 1024, ' '); return std::string(1024 * 1024, ' ');
}); });
auto ft = makeFileTransfer(); auto ft = makeFileTransfer();
FileTransferRequest req(fmt("http://[::1]:%d/index", port)); FileTransferRequest req(boostfmt("http://[::1]:%d/index", port));
req.baseRetryTimeMs = 0; req.baseRetryTimeMs = 0;
auto src = ft->download(std::move(req)); auto src = ft->download(std::move(req));
ASSERT_THROW(src->drain(), FileTransferError); ASSERT_THROW(src->drain(), FileTransferError);
@ -186,7 +186,7 @@ TEST(FileTransfer, NOT_ON_DARWIN(handlesContentEncoding))
auto ft = makeFileTransfer(); auto ft = makeFileTransfer();
StringSink sink; StringSink sink;
ft->download(FileTransferRequest(fmt("http://[::1]:%d/index", port)))->drainInto(sink); ft->download(FileTransferRequest(boostfmt("http://[::1]:%d/index", port)))->drainInto(sink);
EXPECT_EQ(sink.s, original); EXPECT_EQ(sink.s, original);
} }
@ -209,7 +209,7 @@ TEST(FileTransfer, usesIntermediateLinkHeaders)
{"200 ok", "content-length: 1\r\n", [] { return "a"; }}, {"200 ok", "content-length: 1\r\n", [] { return "a"; }},
}); });
auto ft = makeFileTransfer(); auto ft = makeFileTransfer();
FileTransferRequest req(fmt("http://[::1]:%d/first", port)); FileTransferRequest req(boostfmt("http://[::1]:%d/first", port));
req.baseRetryTimeMs = 0; req.baseRetryTimeMs = 0;
auto result = ft->transfer(req); auto result = ft->transfer(req);
ASSERT_EQ(result.immutableUrl, "http://foo"); ASSERT_EQ(result.immutableUrl, "http://foo");