summaryrefslogtreecommitdiff
path: root/nix/libutil
diff options
context:
space:
mode:
Diffstat (limited to 'nix/libutil')
-rw-r--r--nix/libutil/affinity.cc6
-rw-r--r--nix/libutil/archive.cc15
-rw-r--r--nix/libutil/hash.cc27
-rw-r--r--nix/libutil/hash.hh8
-rw-r--r--nix/libutil/serialise.cc2
-rw-r--r--nix/libutil/spawn.cc59
-rw-r--r--nix/libutil/types.hh21
-rw-r--r--nix/libutil/util.cc162
-rw-r--r--nix/libutil/util.hh11
9 files changed, 159 insertions, 152 deletions
diff --git a/nix/libutil/affinity.cc b/nix/libutil/affinity.cc
index 3e21f43a2e..d50e9f3e9c 100644
--- a/nix/libutil/affinity.cc
+++ b/nix/libutil/affinity.cc
@@ -2,6 +2,8 @@
#include "util.hh"
#include "affinity.hh"
+#include <format>
+
#if HAVE_SCHED_H
#include <sched.h>
#endif
@@ -20,12 +22,12 @@ void setAffinityTo(int cpu)
#if HAVE_SCHED_SETAFFINITY
if (sched_getaffinity(0, sizeof(cpu_set_t), &savedAffinity) == -1) return;
didSaveAffinity = true;
- printMsg(lvlDebug, format("locking this thread to CPU %1%") % cpu);
+ printMsg(lvlDebug, std::format("locking this thread to CPU {}", cpu));
cpu_set_t newAffinity;
CPU_ZERO(&newAffinity);
CPU_SET(cpu, &newAffinity);
if (sched_setaffinity(0, sizeof(cpu_set_t), &newAffinity) == -1)
- printMsg(lvlError, format("failed to lock thread to CPU %1%") % cpu);
+ printMsg(lvlError, std::format("failed to lock thread to CPU {}", cpu));
#endif
}
diff --git a/nix/libutil/archive.cc b/nix/libutil/archive.cc
index 54bcd21f93..0df5285860 100644
--- a/nix/libutil/archive.cc
+++ b/nix/libutil/archive.cc
@@ -6,6 +6,7 @@
#include <algorithm>
#include <vector>
#include <map>
+#include <format>
#include <strings.h> // for strcasecmp
@@ -35,7 +36,7 @@ static void dumpContents(const Path & path, size_t size,
writeLongLong(size, sink);
AutoCloseFD fd = open(path.c_str(), O_RDONLY);
- if (fd == -1) throw SysError(format("opening file `%1%'") % path);
+ if (fd == -1) throw SysError(std::format("opening file `{}'", path));
unsigned char buf[65536];
size_t left = size;
@@ -55,7 +56,7 @@ static void dump(const Path & path, Sink & sink, PathFilter & filter)
{
struct stat st;
if (lstat(path.c_str(), &st))
- throw SysError(format("getting attributes of path `%1%'") % path);
+ throw SysError(std::format("getting attributes of path `{}'", path));
writeString("(", sink);
@@ -98,7 +99,7 @@ static void dump(const Path & path, Sink & sink, PathFilter & filter)
writeString(readLink(path), sink);
}
- else throw Error(format("file `%1%' has an unsupported type") % path);
+ else throw Error(std::format("file `{}' has an unsupported type", path));
writeString(")", sink);
}
@@ -227,7 +228,7 @@ static void parse(ParseSink & sink, Source & source, const Path & path)
} else if (s == "name") {
name = readString(source);
if (name.empty() || name == "." || name == ".." || name.find('/') != string::npos || name.find((char) 0) != string::npos)
- throw Error(format("NAR contains invalid file name `%1%'") % name);
+ throw Error(std::format("NAR contains invalid file name `{}'", name));
if (name <= prevName)
throw Error("NAR directory is not sorted");
prevName = name;
@@ -274,7 +275,7 @@ struct RestoreSink : ParseSink
{
Path p = dstPath + path;
if (mkdir(p.c_str(), 0777) == -1)
- throw SysError(format("creating directory `%1%'") % p);
+ throw SysError(std::format("creating directory `{}'", p));
};
void createRegularFile(const Path & path)
@@ -282,7 +283,7 @@ struct RestoreSink : ParseSink
Path p = dstPath + path;
fd.close();
fd = open(p.c_str(), O_CREAT | O_EXCL | O_WRONLY, 0666);
- if (fd == -1) throw SysError(format("creating file `%1%'") % p);
+ if (fd == -1) throw SysError(std::format("creating file `{}'", p));
}
void isExecutable()
@@ -304,7 +305,7 @@ struct RestoreSink : ParseSink
OpenSolaris). Since preallocation is just an
optimisation, ignore it. */
if (errno && errno != EINVAL)
- throw SysError(format("preallocating file of %1% bytes") % len);
+ throw SysError(std::format("preallocating file of {} bytes", len));
}
#endif
}
diff --git a/nix/libutil/hash.cc b/nix/libutil/hash.cc
index 3cb4d05318..57b369d4a9 100644
--- a/nix/libutil/hash.cc
+++ b/nix/libutil/hash.cc
@@ -2,6 +2,9 @@
#include <iostream>
#include <cstring>
+#include <cassert>
+#include <string_view>
+#include <format>
#include "hash.hh"
#include "archive.hh"
@@ -73,18 +76,18 @@ string printHash(const Hash & hash)
}
-Hash parseHash(HashType ht, const string & s)
+Hash parseHash(HashType ht, std::string_view s)
{
Hash hash(ht);
if (s.length() != hash.hashSize * 2) {
string algo = gcry_md_algo_name(ht);
- throw Error(format("invalid %1% hash '%2%' (%3% bytes but expected %4%)")
- % algo % s % (s.length() / 2) % hash.hashSize);
+ throw Error(std::format("invalid {} hash '{}' ({} bytes but expected {})",
+ algo, s, (s.length() / 2), hash.hashSize));
}
for (unsigned int i = 0; i < hash.hashSize; i++) {
string s2(s, i * 2, 2);
if (!isxdigit(s2[0]) || !isxdigit(s2[1]))
- throw Error(format("invalid hash `%1%'") % s);
+ throw Error(std::format("invalid hash `{}'", s));
std::istringstream str(s2);
int n;
str >> std::hex >> n;
@@ -132,7 +135,7 @@ string printHash16or32(const Hash & hash)
}
-Hash parseHash32(HashType ht, const string & s)
+Hash parseHash32(HashType ht, std::string_view s)
{
Hash hash(ht);
unsigned int len = hashLength32(ht);
@@ -144,7 +147,7 @@ Hash parseHash32(HashType ht, const string & s)
for (digit = 0; digit < base32Chars.size(); ++digit) /* !!! slow */
if (base32Chars[digit] == c) break;
if (digit >= 32)
- throw Error(format("invalid base-32 hash '%1%'") % s);
+ throw Error(std::format("invalid base-32 hash '{}'", s));
unsigned int b = n * 5;
unsigned int i = b / 8;
unsigned int j = b % 8;
@@ -156,7 +159,7 @@ Hash parseHash32(HashType ht, const string & s)
}
-Hash parseHash16or32(HashType ht, const string & s)
+Hash parseHash16or32(HashType ht, std::string_view s)
{
Hash hash(ht);
if (s.size() == hash.hashSize * 2)
@@ -166,13 +169,13 @@ Hash parseHash16or32(HashType ht, const string & s)
/* base-32 representation */
hash = parseHash32(ht, s);
else
- throw Error(format("hash `%1%' has wrong length for hash type `%2%'")
- % s % printHashType(ht));
+ throw Error(std::format("hash `{}' has wrong length for hash type `{}'",
+ s, printHashType(ht)));
return hash;
}
-bool isHash(const string & s)
+bool isHash(std::string_view s)
{
if (s.length() != 32) return false;
for (int i = 0; i < 32; i++) {
@@ -247,13 +250,13 @@ Hash hashFile(HashType ht, const Path & path)
start(ht, ctx);
AutoCloseFD fd = open(path.c_str(), O_RDONLY);
- if (fd == -1) throw SysError(format("computing hash of file `%1%'") % path);
+ if (fd == -1) throw SysError(std::format("computing hash of file `{}'", path));
unsigned char buf[8192];
ssize_t n;
while ((n = read(fd, buf, sizeof(buf)))) {
checkInterrupt();
- if (n == -1) throw SysError(format("reading file `%1%'") % path);
+ if (n == -1) throw SysError(std::format("reading file `{}'", path));
update(ht, ctx, buf, n);
}
diff --git a/nix/libutil/hash.hh b/nix/libutil/hash.hh
index ac58651a02..1a6b35f074 100644
--- a/nix/libutil/hash.hh
+++ b/nix/libutil/hash.hh
@@ -51,7 +51,7 @@ struct Hash
string printHash(const Hash & hash);
/* Parse a hexadecimal representation of a hash code. */
-Hash parseHash(HashType ht, const string & s);
+Hash parseHash(HashType ht, std::string_view s);
/* Returns the length of a base-32 hash representation. */
unsigned int hashLength32(const Hash & hash);
@@ -63,13 +63,13 @@ string printHash32(const Hash & hash);
string printHash16or32(const Hash & hash);
/* Parse a base-32 representation of a hash code. */
-Hash parseHash32(HashType ht, const string & s);
+Hash parseHash32(HashType ht, std::string_view s);
/* Parse a base-16 or base-32 representation of a hash code. */
-Hash parseHash16or32(HashType ht, const string & s);
+Hash parseHash16or32(HashType ht, std::string_view s);
/* Verify that the given string is a valid hash code. */
-bool isHash(const string & s);
+bool isHash(std::string_view s);
/* Compute the hash of the given string. */
Hash hashString(HashType ht, const string & s);
diff --git a/nix/libutil/serialise.cc b/nix/libutil/serialise.cc
index 01aeea25c0..befb049c8a 100644
--- a/nix/libutil/serialise.cc
+++ b/nix/libutil/serialise.cc
@@ -3,7 +3,7 @@
#include <cstring>
#include <cerrno>
-
+#include <cassert>
namespace nix {
diff --git a/nix/libutil/spawn.cc b/nix/libutil/spawn.cc
index 7855275494..c25c3a681f 100644
--- a/nix/libutil/spawn.cc
+++ b/nix/libutil/spawn.cc
@@ -30,6 +30,8 @@
#include <cstring>
#include <cstdlib>
#include <cstdint>
+#include <cassert>
+#include <format>
#if HAVE_SYS_MOUNT_H
#include <sys/mount.h>
@@ -61,8 +63,11 @@
#define pivot_root(new_root, put_old) (syscall(SYS_pivot_root, new_root,put_old))
#endif
-
-#define CLONE_ENABLED defined(CLONE_NEWNS)
+#if defined(CLONE_NEWNS)
+#define CLONE_ENABLED 1
+#else
+#define CLONE_ENABLED 0
+#endif
#if CLONE_ENABLED
#include <sys/ioctl.h>
@@ -84,7 +89,7 @@ void addPhaseAfter(Phases & phases, string afterLabel, string addLabel, Action a
phases.insert(i, p);
return;
}
- throw Error(format("label `%1%' not found in phases") % afterLabel);
+ throw Error(std::format("label `{}' not found in phases", afterLabel));
}
@@ -98,7 +103,7 @@ void addPhaseBefore(Phases & phases, string beforeLabel, string addLabel, Action
phases.insert(i, p);
return;
}
- throw Error(format("label `%1%' not found in phases") % beforeLabel);
+ throw Error(std::format("label `{}' not found in phases", beforeLabel));
}
@@ -127,7 +132,7 @@ void deletePhase(Phases & phases, string delLabel)
phases.erase(i);
return;
}
- throw Error(format("label `%1%' not found in phases") % delLabel);
+ throw Error(std::format("label `{}' not found in phases", delLabel));
}
@@ -138,7 +143,7 @@ void replacePhase(Phases & phases, string replaceLabel, Action newAction)
(*i).action = newAction;
return;
}
- throw Error(format("label `%1' not found in phases") % replaceLabel);
+ throw Error(std::format("label `{}' not found in phases", replaceLabel));
}
@@ -190,7 +195,7 @@ static void earlyIOSetupAction(SpawnContext & ctx)
/* Doesn't make sense for it to be writable, but compatibility... */
AutoCloseFD fd = open(ctx.stdinFile.c_str(), O_RDWR);
if(fd == -1)
- throw SysError(format("cannot open `%1%'") % ctx.stdinFile);
+ throw SysError(std::format("cannot open `{}'", ctx.stdinFile));
if(dup2(fd, STDIN_FILENO) == -1)
throw SysError("cannot dup2 fd into stdin fd");
}
@@ -216,7 +221,7 @@ static void chrootAction(SpawnContext & ctx)
if(ctx.doChroot)
#if HAVE_CHROOT
if(chroot(ctx.chrootRootDir.c_str()) == -1)
- throw SysError(format("cannot change root directory to '%1%'") % ctx.chrootRootDir);
+ throw SysError(std::format("cannot change root directory to '{}'", ctx.chrootRootDir));
#else
throw Error("chroot is not supported on this system");
#endif
@@ -227,7 +232,7 @@ static void chdirAction(SpawnContext & ctx)
{
if(ctx.setcwd)
if(chdir(ctx.cwd.c_str()) == -1)
- throw SysError(format("changing into `%1%'") % ctx.cwd);
+ throw SysError(std::format("changing into `{}'", ctx.cwd));
}
@@ -353,7 +358,7 @@ void execAction(SpawnContext & ctx) // kept public for use in 'build.cc'
env = envPtrs.data();
}
if(execvpe(ctx.program.c_str(), stringsToCharPtrs(ctx.args).data(), env) == -1)
- throw SysError(format("executing `%1%'") % ctx.program);
+ throw SysError(std::format("executing `{}'", ctx.program));
}
@@ -478,11 +483,11 @@ static void makeChrootSeparateFilesystemAction(SpawnContext & sctx)
a tmpfs on it. */
if(ctx.mountTmpfsOnChroot) {
if(mount("none", ctx.chrootRootDir.c_str(), "tmpfs", 0, 0) == -1)
- throw SysError(format("unable to mount tmpfs on `%1%'") % ctx.chrootRootDir);
+ throw SysError(std::format("unable to mount tmpfs on `{}'", ctx.chrootRootDir));
}
else {
if(mount(ctx.chrootRootDir.c_str(), ctx.chrootRootDir.c_str(), 0, MS_BIND, 0) == -1)
- throw SysError(format("unable to bind mount ‘%1%’") % ctx.chrootRootDir);
+ throw SysError(std::format("unable to bind mount `{}'", ctx.chrootRootDir));
}
}
#endif
@@ -526,7 +531,7 @@ static void bindMount(Path source, Path target, bool readOnly)
#if HAVE_SYS_MOUNT_H && defined(MS_BIND)
struct stat st;
if (lstat(source.c_str(), &st) == -1)
- throw SysError(format("getting attributes of path `%1%'") % source);
+ throw SysError(std::format("getting attributes of path `{}'", source));
if(S_ISDIR(st.st_mode))
createDirs(target);
@@ -545,11 +550,11 @@ static void bindMount(Path source, Path target, bool readOnly)
while(true){
if(lstat(target.c_str(), &st2) != -1) {
if(!S_ISREG(st2.st_mode))
- throw Error(format("mount target `%1%' exists but is not a regular file") % target);
+ throw Error(std::format("mount target `{}' exists but is not a regular file", target));
break;
}
if(errno != ENOENT) {
- throw SysError(format("stat'ing path `%1%'") % target);
+ throw SysError(std::format("stat'ing path `{}'", target));
}
AutoCloseFD fd = open(target.c_str(),
O_WRONLY | O_NOFOLLOW | O_CREAT | O_EXCL,
@@ -561,7 +566,7 @@ static void bindMount(Path source, Path target, bool readOnly)
/* Note: because of O_CREAT | O_EXCL, EACCES can only mean a
* permission issue with the parent directory */
if(errno != EEXIST)
- throw SysError(format("Creating placeholder regular file target mount `%1%'") % target);
+ throw SysError(std::format("Creating placeholder regular file target mount `{}'", target));
}
}
@@ -569,7 +574,7 @@ static void bindMount(Path source, Path target, bool readOnly)
are in an unprivileged mount namespace and not specifying MS_REC would
reveal subtrees that had been covered up. */
if (mount(source.c_str(), target.c_str(), 0, MS_BIND|MS_REC, 0) == -1)
- throw SysError(format("bind mount from `%1%' to `%2%' failed") % source % target);
+ throw SysError(std::format("bind mount from `{}' to `{}' failed", source, target));
if(readOnly) {
#if defined(MS_REMOUNT) && defined(MS_RDONLY)
/* Extra flags passed with MS_BIND are ignored, hence the extra
@@ -581,12 +586,12 @@ static void bindMount(Path source, Path target, bool readOnly)
#if HAVE_STATVFS
struct statvfs stvfs;
if(statvfs(target.c_str(), &stvfs) == -1)
- throw SysError(format("statvfs of `%1%'") % target);
+ throw SysError(std::format("statvfs of `{}'", target));
mount_flags |= statfsToMountFlags(stvfs.f_flag);
#endif
if (mount(source.c_str(), target.c_str(), 0, mount_flags, 0) == -1)
- throw SysError(format("read-only remount of `%1%' failed") % target);
+ throw SysError(std::format("read-only remount of `{}' failed", target));
#else
throw Error("remounting read-only is not supported on this platform");
#endif
@@ -631,7 +636,7 @@ static void mountProcAction(SpawnContext & sctx)
Path target = (ctx.doChroot ? ctx.chrootRootDir : "") + "/proc";
createDirs(target);
if(mount("none", target.c_str(), "proc", 0, 0) == -1)
- throw SysError(format("mounting `%1%'") % target);
+ throw SysError(std::format("mounting `{}'", target));
}
#endif
}
@@ -645,7 +650,7 @@ static void mountDevshmAction(SpawnContext & sctx)
Path target = (ctx.doChroot ? ctx.chrootRootDir : "") + "/dev/shm";
createDirs(target);
if(mount("none", target.c_str(), "tmpfs", 0, 0) == -1)
- throw SysError(format("mounting `%1%'") % target);
+ throw SysError(std::format("mounting `{}'", target));
}
#endif
}
@@ -661,13 +666,13 @@ static void mountDevptsAction(SpawnContext & sctx)
if(pathExists(chroot + "/dev/ptmx")) return;
createDirs(target);
if(mount("none", target.c_str(), "devpts", 0, "newinstance,mode=0620") == -1)
- throw SysError(format("mounting `%1%'") % target);
+ throw SysError(std::format("mounting `{}'", target));
createSymlink("/dev/pts/ptmx", chroot + "/dev/ptmx");
/* Make sure /dev/pts/ptmx is world-writable. With some Linux
versions, it is created with permissions 0. */
Path targetPtmx = chroot + "/dev/pts/ptmx";
if (chmod(targetPtmx.c_str(), 0666) == -1)
- throw SysError(format("setting permissions on `%1%'") % targetPtmx);
+ throw SysError(std::format("setting permissions on `{}'", targetPtmx));
}
#endif
}
@@ -679,16 +684,16 @@ static void pivotRootAction(SpawnContext & sctx)
CloneSpawnContext & ctx = (CloneSpawnContext &) sctx;
if((ctx.cloneFlags & CLONE_NEWNS) != 0 && ctx.doChroot) {
if (chdir(ctx.chrootRootDir.c_str()) == -1)
- throw SysError(format("cannot change directory to '%1%'") % ctx.chrootRootDir);
+ throw SysError(std::format("cannot change directory to '{}'", ctx.chrootRootDir));
if (mkdir("real-root", 0) == -1)
throw SysError("cannot create real-root directory");
if (pivot_root(".", "real-root") == -1)
- throw SysError(format("cannot pivot old root directory onto '%1%'") % (ctx.chrootRootDir + "/real-root"));
+ throw SysError(std::format("cannot pivot old root directory onto '{}'", (ctx.chrootRootDir + "/real-root")));
if (chroot(".") == -1)
- throw SysError(format("cannot change root directory to '%1%'") % ctx.chrootRootDir);
+ throw SysError(std::format("cannot change root directory to '{}'", ctx.chrootRootDir));
if (umount2("real-root", MNT_DETACH) == -1)
throw SysError("cannot unmount real root filesystem");
@@ -761,7 +766,7 @@ void unshareAndInitUserns(int flags, const string & uidMap,
throw SysError("reaping userns init process");
}
if(!(WIFEXITED(status) != 0 && WEXITSTATUS(status) == EXIT_SUCCESS))
- throw Error(format("userns init child exited with status %1%") % WEXITSTATUS(status));
+ throw Error(std::format("userns init child exited with status {}", WEXITSTATUS(status)));
}
#endif
}
diff --git a/nix/libutil/types.hh b/nix/libutil/types.hh
index 62889e6fa9..1ea5e96c01 100644
--- a/nix/libutil/types.hh
+++ b/nix/libutil/types.hh
@@ -5,8 +5,9 @@
#include <string>
#include <list>
#include <set>
+#include <vector>
+#include <string_view>
-#include <boost/format.hpp>
/* Before 4.7, gcc's std::exception uses empty throw() specifiers for
* its (virtual) destructor and what() in c++11 mode, in violation of spec
@@ -26,16 +27,6 @@ using std::string;
using std::list;
using std::set;
using std::vector;
-using boost::format;
-
-
-struct FormatOrString
-{
- string s;
- FormatOrString(const string & s) : s(s) { };
- FormatOrString(const format & f) : s(f.str()) { };
- FormatOrString(const char * s) : s(s) { };
-};
/* BaseError should generally not be caught, as it has Interrupted as
@@ -47,7 +38,7 @@ protected:
string err;
public:
unsigned int status; // exit status
- BaseError(const FormatOrString & fs, unsigned int status = 1);
+ BaseError(std::string_view fs, unsigned int status = 1);
#ifdef EXCEPTION_NEEDS_THROW_SPEC
~BaseError() throw () { };
const char * what() const throw () { return err.c_str(); }
@@ -56,14 +47,14 @@ public:
#endif
const string & msg() const { return err; }
const string & prefix() const { return prefix_; }
- BaseError & addPrefix(const FormatOrString & fs);
+ BaseError & addPrefix(std::string fs);
};
#define MakeError(newClass, superClass) \
class newClass : public superClass \
{ \
public: \
- newClass(const FormatOrString & fs, unsigned int status = 1) : superClass(fs, status) { }; \
+ newClass(std::string_view fs, unsigned int status = 1) : superClass(fs, status) { }; \
};
MakeError(Error, BaseError)
@@ -72,7 +63,7 @@ class SysError : public Error
{
public:
int errNo;
- SysError(const FormatOrString & fs);
+ SysError(std::string_view fs);
};
diff --git a/nix/libutil/util.cc b/nix/libutil/util.cc
index 77f2547b0a..ddce9879ca 100644
--- a/nix/libutil/util.cc
+++ b/nix/libutil/util.cc
@@ -9,6 +9,8 @@
#include <cstdlib>
#include <sstream>
#include <cstring>
+#include <cassert>
+#include <format>
#include <sys/wait.h>
#include <unistd.h>
@@ -35,22 +37,22 @@ extern char * * environ;
namespace nix {
-BaseError::BaseError(const FormatOrString & fs, unsigned int status)
+BaseError::BaseError(std::string_view fs, unsigned int status)
: status(status)
{
- err = fs.s;
+ err = fs;
}
-BaseError & BaseError::addPrefix(const FormatOrString & fs)
+BaseError & BaseError::addPrefix(std::string fs)
{
- prefix_ = fs.s + prefix_;
+ prefix_ = fs + prefix_;
return *this;
}
-SysError::SysError(const FormatOrString & fs)
- : Error(format("%1%: %2%") % fs.s % strerror(errno))
+SysError::SysError(std::string_view fs)
+ : Error(std::format("{}: {}", fs, strerror(errno)))
, errNo(errno)
{
}
@@ -114,7 +116,7 @@ Path canonPath(const Path & path, bool resolveSymlinks)
string s;
if (path[0] != '/')
- throw Error(format("not an absolute path: `%1%'") % path);
+ throw Error(std::format("not an absolute path: `{}'", path));
string::const_iterator i = path.begin(), end = path.end();
string temp;
@@ -150,7 +152,7 @@ Path canonPath(const Path & path, bool resolveSymlinks)
the symlink target might contain new symlinks). */
if (resolveSymlinks && isLink(s)) {
if (++followCount >= maxFollow)
- throw Error(format("infinite symlink recursion in path `%1%'") % path);
+ throw Error(std::format("infinite symlink recursion in path `{}'", path));
temp = absPath(readLink(s), dirOf(s))
+ string(i, end);
i = temp.begin(); /* restart */
@@ -168,7 +170,7 @@ Path dirOf(const Path & path)
{
Path::size_type pos = path.rfind('/');
if (pos == string::npos)
- throw Error(format("invalid file name `%1%'") % path);
+ throw Error(std::format("invalid file name `{}'", path));
return pos == 0 ? "/" : Path(path, 0, pos);
}
@@ -177,7 +179,7 @@ string baseNameOf(const Path & path)
{
Path::size_type pos = path.rfind('/');
if (pos == string::npos)
- throw Error(format("invalid file name `%1%'") % path);
+ throw Error(std::format("invalid file name `{}'", path));
return string(path, pos + 1);
}
@@ -195,7 +197,7 @@ struct stat lstat(const Path & path)
{
struct stat st;
if (lstat(path.c_str(), &st))
- throw SysError(format("getting status of `%1%'") % path);
+ throw SysError(std::format("getting status of `{}'", path));
return st;
}
@@ -212,7 +214,7 @@ bool pathExists(const Path & path)
#endif
if (!res) return true;
if (errno != ENOENT && errno != ENOTDIR)
- throw SysError(format("getting status of %1%") % path);
+ throw SysError(std::format("getting status of {}", path));
return false;
}
@@ -222,14 +224,14 @@ Path readLink(const Path & path)
checkInterrupt();
struct stat st = lstat(path);
if (!S_ISLNK(st.st_mode))
- throw Error(format("`%1%' is not a symlink") % path);
+ throw Error(std::format("`{}' is not a symlink", path));
std::vector<char> buf(st.st_size);
ssize_t rlsize = readlink(path.c_str(), buf.data(), st.st_size);
if (rlsize == -1)
- throw SysError(format("reading symbolic link '%1%'") % path);
+ throw SysError(std::format("reading symbolic link '{}'", path));
else if (rlsize > st.st_size)
- throw Error(format("symbolic link ‘%1%’ size overflow %2% > %3%")
- % path % rlsize % st.st_size);
+ throw Error(std::format("symbolic link `{}' size overflow {} > {}",
+ path, rlsize, st.st_size));
return string(buf.begin(), buf.end());
}
@@ -253,7 +255,7 @@ static DirEntries readDirectory(DIR *dir)
if (name == "." || name == "..") continue;
entries.emplace_back(name, dirent->d_ino, dirent->d_type);
}
- if (errno) throw SysError(format("reading directory"));
+ if (errno) throw SysError("reading directory");
return entries;
}
@@ -261,7 +263,7 @@ static DirEntries readDirectory(DIR *dir)
DirEntries readDirectory(const Path & path)
{
AutoCloseDir dir = opendir(path.c_str());
- if (!dir) throw SysError(format("opening directory `%1%'") % path);
+ if (!dir) throw SysError(std::format("opening directory `{}'", path));
return readDirectory(dir);
}
@@ -273,7 +275,7 @@ static DirEntries readDirectory(int fd)
if (fdcopy < 0) throw SysError("dup");
AutoCloseDir dir = fdopendir(fdcopy);
- if (!dir) throw SysError(format("opening directory from file descriptor `%1%'") % fd);
+ if (!dir) throw SysError(std::format("opening directory from file descriptor `{}'", fd));
return readDirectory(dir);
}
@@ -304,7 +306,7 @@ string readFile(const Path & path, bool drain)
{
AutoCloseFD fd = open(path.c_str(), O_RDONLY);
if (fd == -1)
- throw SysError(format("reading file `%1%'") % path);
+ throw SysError(std::format("reading file `{}'", path));
return drain ? drainFD(fd) : readFile(fd);
}
@@ -313,7 +315,7 @@ void writeFile(const Path & path, const string & s)
{
AutoCloseFD fd = open(path.c_str(), O_WRONLY | O_TRUNC | O_CREAT, 0666);
if (fd == -1)
- throw SysError(format("writing file '%1%'") % path);
+ throw SysError(std::format("writing file '{}'", path));
writeFull(fd, s);
}
@@ -349,7 +351,7 @@ static void _deletePathAt(int fd, const Path & path, const Path & fullPath, unsi
{
checkInterrupt();
- printMsg(lvlVomit, format("%1%") % fullPath);
+ printMsg(lvlVomit, std::format("{}", fullPath));
#ifdef HAVE_STATX
# define st_mode stx_mode
@@ -364,7 +366,7 @@ static void _deletePathAt(int fd, const Path & path, const Path & fullPath, unsi
struct stat st;
#endif
if (fstatat(fd, path.c_str(), &st, AT_SYMLINK_NOFOLLOW))
- throw SysError(format("getting status of `%1%'") % fullPath);
+ throw SysError(std::format("getting status of `{}'", fullPath));
/* Note: if another process modifies what is at 'path' between now and
when we actually delete it, this may be inaccurate, but I know of no
@@ -380,17 +382,17 @@ static void _deletePathAt(int fd, const Path & path, const Path & fullPath, unsi
O_NOFOLLOW |
O_CLOEXEC);
if(!dirfd.isOpen())
- throw SysError(format("opening `%1%'") % fullPath);
+ throw SysError(std::format("opening `{}'", fullPath));
/* st.st_mode may currently be from a different file than what we
actually opened, get it straight from the file instead */
if(fstat(dirfd, &st))
- throw SysError(format("re-getting status of `%1'") % fullPath);
+ throw SysError(std::format("re-getting status of `{}'", fullPath));
/* Make the directory writable. */
if (!(st.st_mode & S_IWUSR)) {
if (fchmod(dirfd, st.st_mode | S_IWUSR) == -1)
- throw SysError(format("making `%1%' writable") % fullPath);
+ throw SysError(std::format("making `{}' writable", fullPath));
}
for (auto & i : readDirectory(dirfd))
@@ -400,7 +402,7 @@ static void _deletePathAt(int fd, const Path & path, const Path & fullPath, unsi
int ret;
ret = unlinkat(fd, path.c_str(), S_ISDIR(st.st_mode) ? AT_REMOVEDIR : 0 );
if (ret == -1)
- throw SysError(format("cannot unlink `%1%'") % fullPath);
+ throw SysError(std::format("cannot unlink `{}'", fullPath));
#undef st_mode
#undef st_size
@@ -425,7 +427,7 @@ void deletePath(const Path & path)
void deletePath(const Path & path, unsigned long long & bytesFreed, size_t linkThreshold)
{
startNest(nest, lvlDebug,
- format("recursively deleting path `%1%'") % path);
+ std::format("recursively deleting path `{}'", path));
bytesFreed = 0;
_deletePath(path, bytesFreed, linkThreshold);
}
@@ -447,14 +449,14 @@ static void copyFile(int sourceFd, int destinationFd)
}
} else {
if (result < 0)
- throw SysError(format("copy_file_range `%1%' to `%2%'") % sourceFd % destinationFd);
+ throw SysError(std::format("copy_file_range `{}' to `{}'", sourceFd, destinationFd));
/* If 'copy_file_range' copied less than requested, try again. */
for (ssize_t copied = result; copied < st.st_size; copied += result) {
result = copy_file_range(sourceFd, NULL, destinationFd, NULL,
st.st_size - copied, 0);
if (result < 0)
- throw SysError(format("copy_file_range `%1%' to `%2%'") % sourceFd % destinationFd);
+ throw SysError(std::format("copy_file_range `{}' to `{}'", sourceFd, destinationFd));
}
}
}
@@ -465,18 +467,18 @@ static void copyFileRecursively(int sourceroot, const Path &source,
{
struct stat st;
if (fstatat(sourceroot, source.c_str(), &st, AT_SYMLINK_NOFOLLOW) == -1)
- throw SysError(format("statting file `%1%'") % source);
+ throw SysError(std::format("statting file `{}'", source));
if (S_ISREG(st.st_mode)) {
AutoCloseFD sourceFd = openat(sourceroot, source.c_str(),
O_CLOEXEC | O_NOFOLLOW | O_RDONLY);
- if (sourceFd == -1) throw SysError(format("opening `%1%'") % source);
+ if (sourceFd == -1) throw SysError(std::format("opening `{}'", source));
AutoCloseFD destinationFd = openat(destinationroot, destination.c_str(),
O_CLOEXEC | O_CREAT | O_WRONLY | O_TRUNC
| O_NOFOLLOW | O_EXCL,
st.st_mode);
- if (destinationFd == -1) throw SysError(format("opening `%1%'") % source);
+ if (destinationFd == -1) throw SysError(std::format("opening `{}'", source));
copyFile(sourceFd, destinationFd);
fchown(destinationFd, st.st_uid, st.st_gid);
@@ -487,37 +489,37 @@ static void copyFileRecursively(int sourceroot, const Path &source,
target[st.st_size] = '\0';
int err = symlinkat(target.data(), destinationroot, destination.c_str());
if (err != 0)
- throw SysError(format("creating symlink `%1%'") % destination);
+ throw SysError(std::format("creating symlink `{}'", destination));
fchownat(destinationroot, destination.c_str(),
st.st_uid, st.st_gid, AT_SYMLINK_NOFOLLOW);
} else if (S_ISDIR(st.st_mode)) {
int err = mkdirat(destinationroot, destination.c_str(), 0755);
if (err != 0)
- throw SysError(format("creating directory `%1%'") % destination);
+ throw SysError(std::format("creating directory `{}'", destination));
AutoCloseFD destinationFd = openat(destinationroot, destination.c_str(),
O_CLOEXEC | O_RDONLY | O_DIRECTORY
| O_NOFOLLOW);
if (err != 0)
- throw SysError(format("opening directory `%1%'") % destination);
+ throw SysError(std::format("opening directory `{}'", destination));
AutoCloseFD sourceFd = openat(sourceroot, source.c_str(),
O_CLOEXEC | O_NOFOLLOW | O_RDONLY);
if (sourceFd == -1)
- throw SysError(format("opening `%1%'") % source);
+ throw SysError(std::format("opening `{}'", source));
if (deleteSource && !(st.st_mode & S_IWUSR)) {
/* Ensure the directory is writable so files within it can be
deleted. */
if (fchmod(sourceFd, st.st_mode | S_IWUSR) == -1)
- throw SysError(format("making `%1%' directory writable") % source);
+ throw SysError(std::format("making `{}' directory writable", source));
}
for (auto & i : readDirectory(sourceFd))
copyFileRecursively((int)sourceFd, i.name, (int)destinationFd, i.name,
deleteSource);
fchown(destinationFd, st.st_uid, st.st_gid);
- } else throw Error(format("refusing to copy irregular file `%1%'") % source);
+ } else throw Error(std::format("refusing to copy irregular file `{}'", source));
if (deleteSource)
unlinkat(sourceroot, source.c_str(),
@@ -534,9 +536,9 @@ static Path tempName(Path tmpRoot, const Path & prefix, bool includePid,
{
tmpRoot = canonPath(tmpRoot.empty() ? getEnv("TMPDIR", "/tmp") : tmpRoot, true);
if (includePid)
- return (format("%1%/%2%-%3%-%4%") % tmpRoot % prefix % getpid() % counter++).str();
+ return std::format("{}/{}-{}-{}", tmpRoot, prefix, getpid(), counter++);
else
- return (format("%1%/%2%-%3%") % tmpRoot % prefix % counter++).str();
+ return std::format("{}/{}-{}", tmpRoot, prefix, counter++);
}
@@ -560,11 +562,11 @@ Path createTempDir(const Path & tmpRoot, const Path & prefix,
"wheel", then "tar" will fail to unpack archives that
have the setgid bit set on directories. */
if (chown(tmpDir.c_str(), (uid_t) -1, getegid()) != 0)
- throw SysError(format("setting group of directory `%1%'") % tmpDir);
+ throw SysError(std::format("setting group of directory `{}'", tmpDir));
return tmpDir;
}
if (errno != EEXIST)
- throw SysError(format("creating directory `%1%'") % tmpDir);
+ throw SysError(std::format("creating directory `{}'", tmpDir));
}
}
@@ -578,15 +580,15 @@ Paths createDirs(const Path & path)
if (lstat(path.c_str(), &st) == -1) {
created = createDirs(dirOf(path));
if (mkdir(path.c_str(), 0777) == -1 && errno != EEXIST)
- throw SysError(format("creating directory `%1%'") % path);
+ throw SysError(std::format("creating directory `{}'", path));
st = lstat(path);
created.push_back(path);
}
if (S_ISLNK(st.st_mode) && stat(path.c_str(), &st) == -1)
- throw SysError(format("statting symlink `%1%'") % path);
+ throw SysError(std::format("statting symlink `{}'", path));
- if (!S_ISDIR(st.st_mode)) throw Error(format("`%1%' is not a directory") % path);
+ if (!S_ISDIR(st.st_mode)) throw Error(std::format("`{}' is not a directory", path));
return created;
}
@@ -595,7 +597,7 @@ Paths createDirs(const Path & path)
void createSymlink(const Path & target, const Path & link)
{
if (symlink(target.c_str(), link.c_str()))
- throw SysError(format("creating symlink from `%1%' to `%2%'") % link % target);
+ throw SysError(std::format("creating symlink from `{}' to `{}'", link, target));
}
@@ -623,12 +625,12 @@ static string escVerbosity(Verbosity level)
}
-void Nest::open(Verbosity level, const FormatOrString & fs)
+void Nest::open(Verbosity level, std::string_view fs)
{
if (level <= verbosity) {
if (logType == ltEscapes)
std::cerr << "\033[" << escVerbosity(level) << "p"
- << fs.s << "\n";
+ << fs << "\n";
else
printMsg_(level, fs);
nest = true;
@@ -648,7 +650,7 @@ void Nest::close()
}
-void printMsg_(Verbosity level, const FormatOrString & fs)
+void printMsg_(Verbosity level, std::string_view fs)
{
checkInterrupt();
if (level > verbosity) return;
@@ -658,15 +660,15 @@ void printMsg_(Verbosity level, const FormatOrString & fs)
prefix += "| ";
else if (logType == ltEscapes && level != lvlInfo)
prefix = "\033[" + escVerbosity(level) + "s";
- string s = (format("%1%%2%\n") % prefix % fs.s).str();
+ string s = std::format("{}{}\n", prefix, fs);
writeToStderr(s);
}
-void warnOnce(bool & haveWarned, const FormatOrString & fs)
+void warnOnce(bool & haveWarned, std::string_view fs)
{
if (!haveWarned) {
- printMsg(lvlError, format("warning: %1%") % fs.s);
+ printMsg(lvlError, std::format("warning: {}", fs));
haveWarned = true;
}
}
@@ -685,7 +687,7 @@ void writeToStderr(const string & s)
write errors in exception handlers to ensure that cleanup
code runs to completion if the other side of stderr has
been closed unexpectedly. */
- if (!std::uncaught_exception()) throw;
+ if (std::uncaught_exceptions() == 0) throw;
}
}
@@ -754,8 +756,8 @@ void waitForMessage(int fd, const string & message)
string str(message.length(), '\0');
readFull(fd, (unsigned char*)str.data(), message.length());
if (str != message)
- throw Error(format("did not receive message '%1%' on file descriptor %2%")
- % message % fd);
+ throw Error(std::format("did not receive message '{}' on file descriptor {}",
+ message, fd));
}
@@ -777,7 +779,7 @@ AutoDelete::~AutoDelete()
deletePath(path);
else {
if (remove(path.c_str()) == -1)
- throw SysError(format("cannot unlink `%1%'") % path);
+ throw SysError(std::format("cannot unlink `{}'", path));
}
}
} catch (...) {
@@ -848,7 +850,7 @@ void AutoCloseFD::close()
if (fd != -1) {
if (::close(fd) == -1)
/* This should never happen. */
- throw SysError(format("closing file descriptor %1%") % fd);
+ throw SysError(std::format("closing file descriptor {}", fd));
fd = -1;
}
}
@@ -1024,13 +1026,13 @@ void Pid::kill(bool quiet)
if (pid == -1 || pid == 0) return;
if (!quiet)
- printMsg(lvlError, format("killing process %1%") % pid);
+ printMsg(lvlError, std::format("killing process {}", pid));
/* Send the requested signal to the child. If it has its own
process group, send the signal to every process in the child
process group (which hopefully includes *all* its children). */
if (::kill(separatePG ? -pid : pid, killSignal) != 0)
- printMsg(lvlError, (SysError(format("killing process %1%") % pid).msg()));
+ printMsg(lvlError, (SysError(std::format("killing process {}", pid)).msg()));
/* Wait until the child dies, disregarding the exit status. */
int status;
@@ -1038,7 +1040,7 @@ void Pid::kill(bool quiet)
checkInterrupt();
if (errno != EINTR) {
printMsg(lvlError,
- (SysError(format("waiting for process %1%") % pid).msg()));
+ (SysError(std::format("waiting for process {}", pid)).msg()));
break;
}
}
@@ -1079,7 +1081,7 @@ void Pid::setKillSignal(int signal)
void killUser(uid_t uid)
{
- debug(format("killing all processes running under uid `%1%'") % uid);
+ debug(std::format("killing all processes running under uid `{}'", uid));
assert(uid != 0); /* just to be safe... */
@@ -1109,7 +1111,7 @@ void killUser(uid_t uid)
#endif
if (errno == ESRCH) break; /* no more processes */
if (errno != EINTR)
- throw SysError(format("cannot kill processes for uid `%1%'") % uid);
+ throw SysError(std::format("cannot kill processes for uid `{}'", uid));
}
_exit(0);
@@ -1121,7 +1123,7 @@ void killUser(uid_t uid)
if (status == SIGKILL) return;
#endif
if (status != 0)
- throw Error(format("cannot kill processes for uid `%1%': %2%") % uid % statusToString(status));
+ throw Error(std::format("cannot kill processes for uid `{}': {}", uid, statusToString(status)));
/* !!! We should really do some check to make sure that there are
no processes left running under `uid', but there is no portable
@@ -1193,9 +1195,9 @@ string runProgram(Path program, bool searchPath, const Strings & args)
else
execv(program.c_str(), stringsToCharPtrs(args_).data());
- int err = errno;
- printMsg(lvlError, format("executing `%1%': %2%") % program % strerror(err));
- _exit(127);
+ int err = errno;
+ printMsg(lvlError, std::format("executing `{}': {}", program, strerror(err)));
+ _exit(127);
});
pipe.writeSide.close();
@@ -1205,8 +1207,8 @@ string runProgram(Path program, bool searchPath, const Strings & args)
/* Wait for the child to finish. */
int status = pid.wait(true);
if (!statusOk(status))
- throw ExecError(format("program `%1%' %2%")
- % program % statusToString(status));
+ throw ExecError(std::format("program `{}' {}",
+ program, statusToString(status)));
return result;
}
@@ -1256,7 +1258,7 @@ void _interrupted()
/* Block user interrupts while an exception is being handled.
Throwing an exception while another exception is being handled
kills the program! */
- if (!std::uncaught_exception()) {
+ if (std::uncaught_exceptions() == 0) {
_isInterrupted = 0;
throw Interrupted("interrupted by the user");
}
@@ -1319,14 +1321,14 @@ string statusToString(int status)
{
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
if (WIFEXITED(status))
- return (format("failed with exit code %1%") % WEXITSTATUS(status)).str();
+ return std::format("failed with exit code {}", WEXITSTATUS(status));
else if (WIFSIGNALED(status)) {
int sig = WTERMSIG(status);
#if HAVE_STRSIGNAL
const char * description = strsignal(sig);
- return (format("failed due to signal %1% (%2%)") % sig % description).str();
+ return std::format("failed due to signal {} ({})", sig, description);
#else
- return (format("failed due to signal %1%") % sig).str();
+ return std::format("failed due to signal {}", sig);
#endif
}
else
@@ -1347,12 +1349,12 @@ bool hasSuffix(const string & s, const string & suffix)
}
-void expect(std::istream & str, const string & s)
+void expect(std::istream & str, std::string_view s)
{
std::vector<char> s2(s.size());
str.read(s2.data(), s2.size());
if (string(s2.begin(), s2.end()) != s)
- throw FormatError(format("expected string `%1%'") % s);
+ throw FormatError(std::format("expected string `{}'", s));
}
@@ -1411,7 +1413,7 @@ void ignoreException()
try {
throw;
} catch (std::exception & e) {
- printMsg(lvlError, format("error (ignored): %1%") % e.what());
+ printMsg(lvlError, std::format("error (ignored): {}", e.what()));
}
}
@@ -1425,7 +1427,7 @@ void commonChildInit(Pipe & logPipe)
that e.g. ssh cannot open /dev/tty) and it doesn't receive
terminal signals. */
if (setsid() == -1)
- throw SysError(format("creating a new session"));
+ throw SysError("creating a new session");
/* Close the read end so only the parent holds a reference to it. */
logPipe.readSide.close();
@@ -1441,7 +1443,7 @@ void commonChildInit(Pipe & logPipe)
/* Reroute stdin to /dev/null. */
int fdDevNull = open(pathNullDevice.c_str(), O_RDWR);
if (fdDevNull == -1)
- throw SysError(format("cannot open `%1%'") % pathNullDevice);
+ throw SysError(std::format("cannot open `{}'", pathNullDevice));
if (dup2(fdDevNull, STDIN_FILENO) == -1)
throw SysError("cannot dup null device into stdin");
close(fdDevNull);
@@ -1451,7 +1453,7 @@ void commonChildInit(Pipe & logPipe)
Agent::Agent(const string &command, const Strings &args, const std::map<string, string> &env)
{
- debug(format("starting agent '%1%'") % command);
+ debug(std::format("starting agent '{}'", command));
/* Create a pipe to get the output of the child. */
fromAgent.create();
@@ -1487,7 +1489,7 @@ Agent::Agent(const string &command, const Strings &args, const std::map<string,
execv(command.c_str(), stringsToCharPtrs(allArgs).data());
- throw SysError(format("executing `%1%'") % command);
+ throw SysError(std::format("executing `{}'", command));
});
pid.setSeparatePG(true);
diff --git a/nix/libutil/util.hh b/nix/libutil/util.hh
index 7b50dfa5f5..d30dc7801e 100644
--- a/nix/libutil/util.hh
+++ b/nix/libutil/util.hh
@@ -2,6 +2,9 @@
#include "types.hh"
+#include <sstream>
+#include <string_view>
+
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
@@ -139,11 +142,11 @@ private:
public:
Nest();
~Nest();
- void open(Verbosity level, const FormatOrString & fs);
+ void open(Verbosity level, std::string_view fs);
void close();
};
-void printMsg_(Verbosity level, const FormatOrString & fs);
+void printMsg_(Verbosity level, std::string_view fs);
#define startNest(varName, level, f) \
Nest varName; \
@@ -160,7 +163,7 @@ void printMsg_(Verbosity level, const FormatOrString & fs);
#define debug(f) printMsg(lvlDebug, f)
-void warnOnce(bool & haveWarned, const FormatOrString & fs);
+void warnOnce(bool & haveWarned, std::string_view fs);
void writeToStderr(const string & s);
@@ -367,7 +370,7 @@ bool hasSuffix(const string & s, const string & suffix);
/* Read string `s' from stream `str'. */
-void expect(std::istream & str, const string & s);
+void expect(std::istream & str, std::string_view s);
MakeError(FormatError, Error)