From 867055133d3f487e52dd44149f76347c2c28bf10 Mon Sep 17 00:00:00 2001 From: Vincent Ambo Date: Tue, 19 May 2020 18:55:58 +0100 Subject: style(3p/nix): Add braces around single-line conditionals These were not caught by the previous clang-tidy invocation, but were instead sorted out using amber[0] as such: ambr --regex 'if (\(.+\))\s([a-z].*;)' 'if $1 { $2 }' [0]: https://github.com/dalance/amber --- third_party/nix/src/libutil/archive.cc | 36 +++- third_party/nix/src/libutil/args.cc | 40 +++-- third_party/nix/src/libutil/compression.cc | 12 +- third_party/nix/src/libutil/config.cc | 24 ++- third_party/nix/src/libutil/hash.cc | 24 ++- third_party/nix/src/libutil/json.cc | 8 +- third_party/nix/src/libutil/lazy.hh | 4 +- third_party/nix/src/libutil/lru-cache.hh | 12 +- third_party/nix/src/libutil/monitor-fd.hh | 8 +- third_party/nix/src/libutil/pool.hh | 12 +- third_party/nix/src/libutil/ref.hh | 8 +- third_party/nix/src/libutil/serialise.cc | 44 +++-- third_party/nix/src/libutil/thread-pool.cc | 24 ++- third_party/nix/src/libutil/thread-pool.hh | 12 +- third_party/nix/src/libutil/util.cc | 256 +++++++++++++++++++++-------- third_party/nix/src/libutil/util.hh | 4 +- third_party/nix/src/libutil/xml-writer.cc | 16 +- 17 files changed, 408 insertions(+), 136 deletions(-) (limited to 'third_party/nix/src/libutil') diff --git a/third_party/nix/src/libutil/archive.cc b/third_party/nix/src/libutil/archive.cc index c6ee5fcb2a93..a86170b315e6 100644 --- a/third_party/nix/src/libutil/archive.cc +++ b/third_party/nix/src/libutil/archive.cc @@ -46,7 +46,9 @@ static void dumpContents(const Path& path, size_t size, Sink& sink) { sink << "contents" << size; AutoCloseFD fd = open(path.c_str(), O_RDONLY | O_CLOEXEC); - if (!fd) throw SysError(format("opening file '%1%'") % path); + if (!fd) { + throw SysError(format("opening file '%1%'") % path); + } std::vector buf(65536); size_t left = size; @@ -162,7 +164,9 @@ static void parseContents(ParseSink& sink, Source& source, const Path& path) { while (left) { checkInterrupt(); auto n = buf.size(); - if ((unsigned long long)n > left) n = left; + if ((unsigned long long)n > left) { + n = left; + } source(buf.data(), n); sink.receiveContents(buf.data(), n); left -= n; @@ -181,7 +185,9 @@ static void parse(ParseSink& sink, Source& source, const Path& path) { string s; s = readString(source); - if (s != "(") throw badArchive("expected open tag"); + if (s != "(") { + throw badArchive("expected open tag"); + } enum { tpUnknown, tpRegular, tpDirectory, tpSymlink } type = tpUnknown; @@ -197,7 +203,9 @@ static void parse(ParseSink& sink, Source& source, const Path& path) { } else if (s == "type") { - if (type != tpUnknown) throw badArchive("multiple type fields"); + if (type != tpUnknown) { + throw badArchive("multiple type fields"); + } string t = readString(source); if (t == "regular") { @@ -225,7 +233,9 @@ static void parse(ParseSink& sink, Source& source, const Path& path) { else if (s == "executable" && type == tpRegular) { auto s = readString(source); - if (s != "") throw badArchive("executable marker has non-empty value"); + if (s != "") { + throw badArchive("executable marker has non-empty value"); + } sink.isExecutable(); } @@ -233,7 +243,9 @@ static void parse(ParseSink& sink, Source& source, const Path& path) { string name, prevName; s = readString(source); - if (s != "(") throw badArchive("expected open tag"); + if (s != "(") { + throw badArchive("expected open tag"); + } while (1) { checkInterrupt(); @@ -248,7 +260,9 @@ static void parse(ParseSink& sink, Source& source, const Path& path) { name.find('/') != string::npos || name.find((char)0) != string::npos) throw Error(format("NAR contains invalid file name '%1%'") % name); - if (name <= prevName) throw Error("NAR directory is not sorted"); + if (name <= prevName) { + throw Error("NAR directory is not sorted"); + } prevName = name; if (archiveSettings.useCaseHack) { auto i = names.find(name); @@ -306,12 +320,16 @@ struct RestoreSink : ParseSink { void createRegularFile(const Path& path) { Path p = dstPath + path; fd = open(p.c_str(), O_CREAT | O_EXCL | O_WRONLY | O_CLOEXEC, 0666); - if (!fd) throw SysError(format("creating file '%1%'") % p); + if (!fd) { + throw SysError(format("creating file '%1%'") % p); + } } void isExecutable() { struct stat st; - if (fstat(fd.get(), &st) == -1) throw SysError("fstat"); + if (fstat(fd.get(), &st) == -1) { + throw SysError("fstat"); + } if (fchmod(fd.get(), st.st_mode | (S_IXUSR | S_IXGRP | S_IXOTH)) == -1) throw SysError("fchmod"); } diff --git a/third_party/nix/src/libutil/args.cc b/third_party/nix/src/libutil/args.cc index 2199099e7cba..cfe68ad6a055 100644 --- a/third_party/nix/src/libutil/args.cc +++ b/third_party/nix/src/libutil/args.cc @@ -9,7 +9,9 @@ Args::FlagMaker Args::mkFlag() { return FlagMaker(*this); } Args::FlagMaker::~FlagMaker() { assert(flag->longName != ""); args.longFlags[flag->longName] = flag; - if (flag->shortName) args.shortFlags[flag->shortName] = flag; + if (flag->shortName) { + args.shortFlags[flag->shortName] = flag; + } } void Args::parseCmdline(const Strings& _cmdline) { @@ -46,7 +48,9 @@ void Args::parseCmdline(const Strings& _cmdline) { throw UsageError(format("unrecognised flag '%1%'") % arg); } else { pendingArgs.push_back(*pos++); - if (processArgs(pendingArgs, false)) pendingArgs.clear(); + if (processArgs(pendingArgs, false)) { + pendingArgs.clear(); + } } } @@ -58,13 +62,19 @@ void Args::printHelp(const string& programName, std::ostream& out) { for (auto& exp : expectedArgs) { std::cout << renderLabels({exp.label}); // FIXME: handle arity > 1 - if (exp.arity == 0) std::cout << "..."; - if (exp.optional) std::cout << "?"; + if (exp.arity == 0) { + std::cout << "..."; + } + if (exp.optional) { + std::cout << "?"; + } } std::cout << "\n"; auto s = description(); - if (s != "") std::cout << "\nSummary: " << s << ".\n"; + if (s != "") { + std::cout << "\nSummary: " << s << ".\n"; + } if (longFlags.size()) { std::cout << "\n"; @@ -76,7 +86,9 @@ void Args::printHelp(const string& programName, std::ostream& out) { void Args::printFlags(std::ostream& out) { Table2 table; for (auto& flag : longFlags) { - if (hiddenCategories.count(flag.second->category)) continue; + if (hiddenCategories.count(flag.second->category)) { + continue; + } table.push_back(std::make_pair( (flag.second->shortName ? std::string("-") + flag.second->shortName + ", " @@ -95,7 +107,9 @@ bool Args::processFlag(Strings::iterator& pos, Strings::iterator end) { std::vector args; for (size_t n = 0; n < flag.arity; ++n) { if (pos == end) { - if (flag.arity == ArityAny) break; + if (flag.arity == ArityAny) { + break; + } throw UsageError(format("flag '%1%' requires %2% argument(s)") % name % flag.arity); } @@ -107,14 +121,18 @@ bool Args::processFlag(Strings::iterator& pos, Strings::iterator end) { if (string(*pos, 0, 2) == "--") { auto i = longFlags.find(string(*pos, 2)); - if (i == longFlags.end()) return false; + if (i == longFlags.end()) { + return false; + } return process("--" + i->first, *i->second); } if (string(*pos, 0, 1) == "-" && pos->size() == 2) { auto c = (*pos)[1]; auto i = shortFlags.find(c); - if (i == shortFlags.end()) return false; + if (i == shortFlags.end()) { + return false; + } return process(std::string("-") + c, *i->second); } @@ -153,7 +171,9 @@ Args::FlagMaker& Args::FlagMaker::mkHashTypeFlag(HashType* ht) { description("hash algorithm ('md5', 'sha1', 'sha256', or 'sha512')"); handler([ht](std::string s) { *ht = parseHashType(s); - if (*ht == htUnknown) throw UsageError("unknown hash type '%1%'", s); + if (*ht == htUnknown) { + throw UsageError("unknown hash type '%1%'", s); + } }); return *this; } diff --git a/third_party/nix/src/libutil/compression.cc b/third_party/nix/src/libutil/compression.cc index b025e33683c8..219d9046fa65 100644 --- a/third_party/nix/src/libutil/compression.cc +++ b/third_party/nix/src/libutil/compression.cc @@ -138,7 +138,9 @@ struct BrotliDecompressionSink : ChunkedCompressionSink { BrotliDecompressionSink(Sink& nextSink) : nextSink(nextSink) { state = BrotliDecoderCreateInstance(nullptr, nullptr, nullptr); - if (!state) throw CompressionError("unable to initialize brotli decoder"); + if (!state) { + throw CompressionError("unable to initialize brotli decoder"); + } } ~BrotliDecompressionSink() { BrotliDecoderDestroyInstance(state); } @@ -214,7 +216,9 @@ struct XzCompressionSink : CompressionSink { mt_options.check = LZMA_CHECK_CRC64; mt_options.threads = lzma_cputhreads(); mt_options.block_size = 0; - if (mt_options.threads == 0) mt_options.threads = 1; + if (mt_options.threads == 0) { + mt_options.threads = 1; + } // FIXME: maybe use lzma_stream_encoder_mt_memusage() to control the // number of threads. ret = lzma_stream_encoder_mt(&strm, &mt_options); @@ -322,7 +326,9 @@ struct BrotliCompressionSink : ChunkedCompressionSink { BrotliCompressionSink(Sink& nextSink) : nextSink(nextSink) { state = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr); - if (!state) throw CompressionError("unable to initialise brotli encoder"); + if (!state) { + throw CompressionError("unable to initialise brotli encoder"); + } } ~BrotliCompressionSink() { BrotliEncoderDestroyInstance(state); } diff --git a/third_party/nix/src/libutil/config.cc b/third_party/nix/src/libutil/config.cc index 83dbf8b6e54f..dbb703750f36 100644 --- a/third_party/nix/src/libutil/config.cc +++ b/third_party/nix/src/libutil/config.cc @@ -11,7 +11,9 @@ namespace nix { bool Config::set(const std::string& name, const std::string& value) { auto i = _settings.find(name); - if (i == _settings.end()) return false; + if (i == _settings.end()) { + return false; + } i->second.setting->set(value); i->second.setting->overriden = true; return true; @@ -84,10 +86,14 @@ void AbstractConfig::applyConfigFile(const Path& path) { pos++; string::size_type hash = line.find('#'); - if (hash != string::npos) line = string(line, 0, hash); + if (hash != string::npos) { + line = string(line, 0, hash); + } vector tokens = tokenizeString >(line); - if (tokens.empty()) continue; + if (tokens.empty()) { + continue; + } if (tokens.size() < 2) throw UsageError("illegal configuration line '%1%' in '%2%'", line, @@ -147,7 +153,9 @@ void Config::toJSON(JSONObject& out) { void Config::convertToArgs(Args& args, const std::string& category) { for (auto& s : _settings) - if (!s.second.isAlias) s.second.setting->convertToArg(args, category); + if (!s.second.isAlias) { + s.second.setting->convertToArg(args, category); + } } AbstractSetting::AbstractSetting(const std::string& name, @@ -284,7 +292,9 @@ void PathSetting::set(const std::string& str) { bool GlobalConfig::set(const std::string& name, const std::string& value) { for (auto& config : *configRegistrations) - if (config->set(name, value)) return true; + if (config->set(name, value)) { + return true; + } unknownSettings.emplace(name, value); @@ -315,7 +325,9 @@ GlobalConfig globalConfig; GlobalConfig::ConfigRegistrations* GlobalConfig::configRegistrations; GlobalConfig::Register::Register(Config* config) { - if (!configRegistrations) configRegistrations = new ConfigRegistrations; + if (!configRegistrations) { + configRegistrations = new ConfigRegistrations; + } configRegistrations->emplace_back(config); } diff --git a/third_party/nix/src/libutil/hash.cc b/third_party/nix/src/libutil/hash.cc index d303a4f5b97d..0a0869dd4e8c 100644 --- a/third_party/nix/src/libutil/hash.cc +++ b/third_party/nix/src/libutil/hash.cc @@ -139,7 +139,9 @@ Hash::Hash(const std::string& s, HashType type) : type(type) { if (sep != string::npos) { string hts = string(s, 0, sep); this->type = parseHashType(hts); - if (this->type == htUnknown) throw BadHash("unknown hash type '%s'", hts); + if (this->type == htUnknown) { + throw BadHash("unknown hash type '%s'", hts); + } if (type != htUnknown && type != this->type) throw BadHash("hash '%s' should have type '%s'", s, printHashType(type)); pos = sep + 1; @@ -174,8 +176,12 @@ Hash::Hash(const std::string& s, HashType type) : type(type) { char c = s[pos + size - n - 1]; unsigned char digit; for (digit = 0; digit < base32Chars.size(); ++digit) /* !!! slow */ - if (base32Chars[digit] == c) break; - if (digit >= 32) throw BadHash("invalid base-32 hash '%s'", s); + if (base32Chars[digit] == c) { + break; + } + if (digit >= 32) { + throw BadHash("invalid base-32 hash '%s'", s); + } unsigned int b = n * 5; unsigned int i = b / 8; unsigned int j = b % 8; @@ -184,7 +190,9 @@ Hash::Hash(const std::string& s, HashType type) : type(type) { if (i < hashSize - 1) { hash[i + 1] |= digit >> (8 - j); } else { - if (digit >> (8 - j)) throw BadHash("invalid base-32 hash '%s'", s); + if (digit >> (8 - j)) { + throw BadHash("invalid base-32 hash '%s'", s); + } } } } @@ -258,13 +266,17 @@ Hash hashFile(HashType ht, const Path& path) { start(ht, ctx); AutoCloseFD fd = open(path.c_str(), O_RDONLY | O_CLOEXEC); - if (!fd) throw SysError(format("opening file '%1%'") % path); + if (!fd) { + throw SysError(format("opening file '%1%'") % path); + } std::vector buf(8192); ssize_t n; while ((n = read(fd.get(), buf.data(), buf.size()))) { checkInterrupt(); - if (n == -1) throw SysError(format("reading file '%1%'") % path); + if (n == -1) { + throw SysError(format("reading file '%1%'") % path); + } update(ht, ctx, buf.data(), n); } diff --git a/third_party/nix/src/libutil/json.cc b/third_party/nix/src/libutil/json.cc index 8746ca9a6947..7965f4725ba4 100644 --- a/third_party/nix/src/libutil/json.cc +++ b/third_party/nix/src/libutil/json.cc @@ -91,7 +91,9 @@ JSONWriter::~JSONWriter() { if (state) { assertActive(); state->stack--; - if (state->stack == 0) delete state; + if (state->stack == 0) { + delete state; + } } } @@ -158,7 +160,9 @@ void JSONObject::attr(const std::string& s) { comma(); toJSON(state->str, s); state->str << ':'; - if (state->indent) state->str << ' '; + if (state->indent) { + state->str << ' '; + } } JSONList JSONObject::list(const std::string& name) { diff --git a/third_party/nix/src/libutil/lazy.hh b/third_party/nix/src/libutil/lazy.hh index 9807b7540620..b564b481fc38 100644 --- a/third_party/nix/src/libutil/lazy.hh +++ b/third_party/nix/src/libutil/lazy.hh @@ -35,7 +35,9 @@ class Lazy { ex = std::current_exception(); } }); - if (ex) std::rethrow_exception(ex); + if (ex) { + std::rethrow_exception(ex); + } return value; } }; diff --git a/third_party/nix/src/libutil/lru-cache.hh b/third_party/nix/src/libutil/lru-cache.hh index bf7263243c31..f6fcdaf82ebd 100644 --- a/third_party/nix/src/libutil/lru-cache.hh +++ b/third_party/nix/src/libutil/lru-cache.hh @@ -31,7 +31,9 @@ class LRUCache { /* Insert or upsert an item in the cache. */ void upsert(const Key& key, const Value& value) { - if (capacity == 0) return; + if (capacity == 0) { + return; + } erase(key); @@ -53,7 +55,9 @@ class LRUCache { bool erase(const Key& key) { auto i = data.find(key); - if (i == data.end()) return false; + if (i == data.end()) { + return false; + } lru.erase(i->second.first.it); data.erase(i); return true; @@ -63,7 +67,9 @@ class LRUCache { recently used item. */ std::optional get(const Key& key) { auto i = data.find(key); - if (i == data.end()) return {}; + if (i == data.end()) { + return {}; + } /* Move this item to the back of the LRU list. */ lru.erase(i->second.first.it); diff --git a/third_party/nix/src/libutil/monitor-fd.hh b/third_party/nix/src/libutil/monitor-fd.hh index 54e9de848a13..c818c5826116 100644 --- a/third_party/nix/src/libutil/monitor-fd.hh +++ b/third_party/nix/src/libutil/monitor-fd.hh @@ -28,7 +28,9 @@ class MonitorFdHup { */ fds[0].events = POLLHUP; auto count = poll(fds, 1, -1); - if (count == -1) abort(); // can't happen + if (count == -1) { + abort(); + } // can't happen /* This shouldn't happen, but can on macOS due to a bug. See rdar://37550628. @@ -36,7 +38,9 @@ class MonitorFdHup { coordination with the main thread if spinning proves too harmful. */ - if (count == 0) continue; + if (count == 0) { + continue; + } assert(fds[0].revents & POLLHUP); triggerInterrupt(); break; diff --git a/third_party/nix/src/libutil/pool.hh b/third_party/nix/src/libutil/pool.hh index e25d82d8ec11..6d70795d35ac 100644 --- a/third_party/nix/src/libutil/pool.hh +++ b/third_party/nix/src/libutil/pool.hh @@ -99,10 +99,14 @@ class Pool { Handle(const Handle& l) = delete; ~Handle() { - if (!r) return; + if (!r) { + return; + } { auto state_(pool.state.lock()); - if (!bad) state_->idle.push_back(ref(r)); + if (!bad) { + state_->idle.push_back(ref(r)); + } assert(state_->inUse); state_->inUse--; } @@ -160,7 +164,9 @@ class Pool { auto state_(state.lock()); std::vector> left; for (auto& p : state_->idle) - if (validator(p)) left.push_back(p); + if (validator(p)) { + left.push_back(p); + } std::swap(state_->idle, left); } }; diff --git a/third_party/nix/src/libutil/ref.hh b/third_party/nix/src/libutil/ref.hh index 5f0d7db4b6a1..063e6b327c22 100644 --- a/third_party/nix/src/libutil/ref.hh +++ b/third_party/nix/src/libutil/ref.hh @@ -17,11 +17,15 @@ class ref { ref(const ref& r) : p(r.p) {} explicit ref(const std::shared_ptr& p) : p(p) { - if (!p) throw std::invalid_argument("null pointer cast to ref"); + if (!p) { + throw std::invalid_argument("null pointer cast to ref"); + } } explicit ref(T* p) : p(p) { - if (!p) throw std::invalid_argument("null pointer cast to ref"); + if (!p) { + throw std::invalid_argument("null pointer cast to ref"); + } } T* operator->() const { return &*p; } diff --git a/third_party/nix/src/libutil/serialise.cc b/third_party/nix/src/libutil/serialise.cc index 079b88c1cfc4..760d19ed4cf3 100644 --- a/third_party/nix/src/libutil/serialise.cc +++ b/third_party/nix/src/libutil/serialise.cc @@ -11,7 +11,9 @@ namespace nix { void BufferedSink::operator()(const unsigned char* data, size_t len) { - if (!buffer) buffer = decltype(buffer)(new unsigned char[bufSize]); + if (!buffer) { + buffer = decltype(buffer)(new unsigned char[bufSize]); + } while (len) { /* Optimisation: bypass the buffer if the data exceeds the @@ -28,12 +30,16 @@ void BufferedSink::operator()(const unsigned char* data, size_t len) { data += n; bufPos += n; len -= n; - if (bufPos == bufSize) flush(); + if (bufPos == bufSize) { + flush(); + } } } void BufferedSink::flush() { - if (bufPos == 0) return; + if (bufPos == 0) { + return; + } size_t n = bufPos; bufPos = 0; // don't trigger the assert() in ~BufferedSink() write(buffer.get(), n); @@ -97,15 +103,21 @@ std::string Source::drain() { } size_t BufferedSource::read(unsigned char* data, size_t len) { - if (!buffer) buffer = decltype(buffer)(new unsigned char[bufSize]); + if (!buffer) { + buffer = decltype(buffer)(new unsigned char[bufSize]); + } - if (!bufPosIn) bufPosIn = readUnbuffered(buffer.get(), bufSize); + if (!bufPosIn) { + bufPosIn = readUnbuffered(buffer.get(), bufSize); + } /* Copy out the data in the buffer. */ size_t n = len > bufPosIn - bufPosOut ? bufPosIn - bufPosOut : len; memcpy(data, buffer.get() + bufPosOut, n); bufPosOut += n; - if (bufPosIn == bufPosOut) bufPosIn = bufPosOut = 0; + if (bufPosIn == bufPosOut) { + bufPosIn = bufPosOut = 0; + } return n; } @@ -132,7 +144,9 @@ size_t FdSource::readUnbuffered(unsigned char* data, size_t len) { bool FdSource::good() { return _good; } size_t StringSource::read(unsigned char* data, size_t len) { - if (pos == s.size()) throw EndOfFile("end of string reached"); + if (pos == s.size()) { + throw EndOfFile("end of string reached"); + } size_t n = s.copy((char*)data, len, pos); pos += n; return n; @@ -162,7 +176,9 @@ std::unique_ptr sinkToSource(std::function fun, if (!coro) coro = coro_t::pull_type([&](coro_t::push_type& yield) { LambdaSink sink([&](const unsigned char* data, size_t len) { - if (len) yield(std::string((const char*)data, len)); + if (len) { + yield(std::string((const char*)data, len)); + } }); fun(sink); }); @@ -232,13 +248,17 @@ void readPadding(size_t len, Source& source) { size_t n = 8 - (len % 8); source(zero, n); for (unsigned int i = 0; i < n; i++) - if (zero[i]) throw SerialisationError("non-zero padding"); + if (zero[i]) { + throw SerialisationError("non-zero padding"); + } } } size_t readString(unsigned char* buf, size_t max, Source& source) { auto len = readNum(source); - if (len > max) throw SerialisationError("string is too long"); + if (len > max) { + throw SerialisationError("string is too long"); + } source(buf, len); readPadding(len, source); return len; @@ -246,7 +266,9 @@ size_t readString(unsigned char* buf, size_t max, Source& source) { string readString(Source& source, size_t max) { auto len = readNum(source); - if (len > max) throw SerialisationError("string is too long"); + if (len > max) { + throw SerialisationError("string is too long"); + } std::string res(len, 0); source((unsigned char*)res.data(), len); readPadding(len, source); diff --git a/third_party/nix/src/libutil/thread-pool.cc b/third_party/nix/src/libutil/thread-pool.cc index ee727aacd02a..a16f4c2b6033 100644 --- a/third_party/nix/src/libutil/thread-pool.cc +++ b/third_party/nix/src/libutil/thread-pool.cc @@ -10,7 +10,9 @@ ThreadPool::ThreadPool(size_t _maxThreads) : maxThreads(_maxThreads) { if (!maxThreads) { maxThreads = std::thread::hardware_concurrency(); - if (!maxThreads) maxThreads = 1; + if (!maxThreads) { + maxThreads = 1; + } } DLOG(INFO) << "starting pool of " << maxThreads - 1 << " threads"; @@ -26,7 +28,9 @@ void ThreadPool::shutdown() { std::swap(workers, state->workers); } - if (workers.empty()) return; + if (workers.empty()) { + return; + } DLOG(INFO) << "reaping " << workers.size() << " worker threads"; @@ -62,7 +66,9 @@ void ThreadPool::process() { assert(quit); - if (state->exception) std::rethrow_exception(state->exception); + if (state->exception) { + std::rethrow_exception(state->exception); + } } catch (...) { /* In the exceptional case, some workers may still be @@ -76,7 +82,9 @@ void ThreadPool::process() { } void ThreadPool::doWork(bool mainThread) { - if (!mainThread) interruptCheck = [&]() { return (bool)quit; }; + if (!mainThread) { + interruptCheck = [&]() { return (bool)quit; }; + } bool didWork = false; std::exception_ptr exc; @@ -114,9 +122,13 @@ void ThreadPool::doWork(bool mainThread) { /* Wait until a work item is available or we're asked to quit. */ while (true) { - if (quit) return; + if (quit) { + return; + } - if (!state->pending.empty()) break; + if (!state->pending.empty()) { + break; + } /* If there are no active or pending items, and the main thread is running process(), then no new items diff --git a/third_party/nix/src/libutil/thread-pool.hh b/third_party/nix/src/libutil/thread-pool.hh index d709c9dbc855..114dae40eec9 100644 --- a/third_party/nix/src/libutil/thread-pool.hh +++ b/third_party/nix/src/libutil/thread-pool.hh @@ -78,7 +78,9 @@ void processGraph(ThreadPool& pool, const std::set& nodes, { auto graph(graph_.lock()); auto i = graph->refs.find(node); - if (i == graph->refs.end()) goto getRefs; + if (i == graph->refs.end()) { + goto getRefs; + } goto doWork; } @@ -93,7 +95,9 @@ void processGraph(ThreadPool& pool, const std::set& nodes, graph->refs[node].insert(ref); graph->rrefs[ref].insert(node); } - if (graph->refs[node].empty()) goto doWork; + if (graph->refs[node].empty()) { + goto doWork; + } } } @@ -111,7 +115,9 @@ void processGraph(ThreadPool& pool, const std::set& nodes, auto i = refs.find(node); assert(i != refs.end()); refs.erase(i); - if (refs.empty()) pool.enqueue(std::bind(worker, rref)); + if (refs.empty()) { + pool.enqueue(std::bind(worker, rref)); + } } graph->left.erase(node); graph->refs.erase(node); diff --git a/third_party/nix/src/libutil/util.cc b/third_party/nix/src/libutil/util.cc index 1740d1f256d0..0a2887501c8e 100644 --- a/third_party/nix/src/libutil/util.cc +++ b/third_party/nix/src/libutil/util.cc @@ -107,7 +107,9 @@ Path canonPath(const Path& path, bool resolveSymlinks) { string s; - if (path[0] != '/') throw Error(format("not an absolute path: '%1%'") % path); + if (path[0] != '/') { + throw Error(format("not an absolute path: '%1%'") % path); + } string::const_iterator i = path.begin(), end = path.end(); string temp; @@ -119,15 +121,21 @@ Path canonPath(const Path& path, bool resolveSymlinks) { while (1) { /* Skip slashes. */ while (i != end && *i == '/') i++; - if (i == end) break; + if (i == end) { + break; + } /* Ignore `.'. */ - if (*i == '.' && (i + 1 == end || i[1] == '/')) i++; + if (*i == '.' && (i + 1 == end || i[1] == '/')) { + i++; + } /* If `..', delete the last component. */ else if (*i == '.' && i + 1 < end && i[1] == '.' && (i + 2 == end || i[2] == '/')) { - if (!s.empty()) s.erase(s.rfind('/')); + if (!s.empty()) { + s.erase(s.rfind('/')); + } i += 2; } @@ -155,15 +163,21 @@ Path canonPath(const Path& path, bool resolveSymlinks) { Path dirOf(const Path& path) { Path::size_type pos = path.rfind('/'); - if (pos == string::npos) return "."; + if (pos == string::npos) { + return "."; + } return pos == 0 ? "/" : Path(path, 0, pos); } string baseNameOf(const Path& path) { - if (path.empty()) return ""; + if (path.empty()) { + return ""; + } Path::size_type last = path.length() - 1; - if (path[last] == '/' && last > 0) last -= 1; + if (path[last] == '/' && last > 0) { + last -= 1; + } Path::size_type pos = path.rfind('/', last); if (pos == string::npos) @@ -228,13 +242,17 @@ DirEntries readDirectory(const Path& path) { entries.reserve(64); AutoCloseDir dir(opendir(path.c_str())); - if (!dir) throw SysError(format("opening directory '%1%'") % path); + if (!dir) { + throw SysError(format("opening directory '%1%'") % path); + } struct dirent* dirent; while (errno = 0, dirent = readdir(dir.get())) { /* sic */ checkInterrupt(); string name = dirent->d_name; - if (name == "." || name == "..") continue; + if (name == "." || name == "..") { + continue; + } entries.emplace_back(name, dirent->d_ino, #ifdef HAVE_STRUCT_DIRENT_D_TYPE dirent->d_type @@ -243,22 +261,32 @@ DirEntries readDirectory(const Path& path) { #endif ); } - if (errno) throw SysError(format("reading directory '%1%'") % path); + if (errno) { + throw SysError(format("reading directory '%1%'") % path); + } return entries; } unsigned char getFileType(const Path& path) { struct stat st = lstat(path); - if (S_ISDIR(st.st_mode)) return DT_DIR; - if (S_ISLNK(st.st_mode)) return DT_LNK; - if (S_ISREG(st.st_mode)) return DT_REG; + if (S_ISDIR(st.st_mode)) { + return DT_DIR; + } + if (S_ISLNK(st.st_mode)) { + return DT_LNK; + } + if (S_ISREG(st.st_mode)) { + return DT_REG; + } return DT_UNKNOWN; } string readFile(int fd) { struct stat st; - if (fstat(fd, &st) == -1) throw SysError("statting file"); + if (fstat(fd, &st) == -1) { + throw SysError("statting file"); + } std::vector buf(st.st_size); readFull(fd, buf.data(), st.st_size); @@ -268,27 +296,35 @@ string readFile(int fd) { string readFile(const Path& path, bool drain) { AutoCloseFD fd = open(path.c_str(), O_RDONLY | O_CLOEXEC); - if (!fd) throw SysError(format("opening file '%1%'") % path); + if (!fd) { + throw SysError(format("opening file '%1%'") % path); + } return drain ? drainFD(fd.get()) : readFile(fd.get()); } void readFile(const Path& path, Sink& sink) { AutoCloseFD fd = open(path.c_str(), O_RDONLY | O_CLOEXEC); - if (!fd) throw SysError("opening file '%s'", path); + if (!fd) { + throw SysError("opening file '%s'", path); + } drainFD(fd.get(), sink); } void writeFile(const Path& path, const string& s, mode_t mode) { AutoCloseFD fd = open(path.c_str(), O_WRONLY | O_TRUNC | O_CREAT | O_CLOEXEC, mode); - if (!fd) throw SysError(format("opening file '%1%'") % path); + if (!fd) { + throw SysError(format("opening file '%1%'") % path); + } writeFull(fd.get(), s); } void writeFile(const Path& path, Source& source, mode_t mode) { AutoCloseFD fd = open(path.c_str(), O_WRONLY | O_TRUNC | O_CREAT | O_CLOEXEC, mode); - if (!fd) throw SysError(format("opening file '%1%'") % path); + if (!fd) { + throw SysError(format("opening file '%1%'") % path); + } std::vector buf(64 * 1024); @@ -310,11 +346,15 @@ string readLine(int fd) { // FIXME: inefficient ssize_t rd = read(fd, &ch, 1); if (rd == -1) { - if (errno != EINTR) throw SysError("reading a line"); + if (errno != EINTR) { + throw SysError("reading a line"); + } } else if (rd == 0) throw EndOfFile("unexpected EOF reading a line"); else { - if (ch == '\n') return s; + if (ch == '\n') { + return s; + } s += ch; } } @@ -330,11 +370,15 @@ static void _deletePath(const Path& path, unsigned long long& bytesFreed) { struct stat st; if (lstat(path.c_str(), &st) == -1) { - if (errno == ENOENT) return; + if (errno == ENOENT) { + return; + } throw SysError(format("getting status of '%1%'") % path); } - if (!S_ISDIR(st.st_mode) && st.st_nlink == 1) bytesFreed += st.st_size; + if (!S_ISDIR(st.st_mode) && st.st_nlink == 1) { + bytesFreed += st.st_size; + } if (S_ISDIR(st.st_mode)) { /* Make the directory accessible. */ @@ -349,7 +393,9 @@ static void _deletePath(const Path& path, unsigned long long& bytesFreed) { } if (remove(path.c_str()) == -1) { - if (errno == ENOENT) return; + if (errno == ENOENT) { + return; + } throw SysError(format("cannot unlink '%1%'") % path); } } @@ -409,7 +455,9 @@ Path createTempDir(const Path& tmpRoot, const Path& prefix, bool includePid, std::string getUserName() { auto pw = getpwuid(geteuid()); std::string name = pw ? pw->pw_name : getEnv("USER", ""); - if (name.empty()) throw Error("cannot figure out user name"); + if (name.empty()) { + throw Error("cannot figure out user name"); + } return name; } @@ -431,13 +479,17 @@ Path getHome() { return getHome2(); } Path getCacheDir() { Path cacheDir = getEnv("XDG_CACHE_HOME"); - if (cacheDir.empty()) cacheDir = getHome() + "/.cache"; + if (cacheDir.empty()) { + cacheDir = getHome() + "/.cache"; + } return cacheDir; } Path getConfigDir() { Path configDir = getEnv("XDG_CONFIG_HOME"); - if (configDir.empty()) configDir = getHome() + "/.config"; + if (configDir.empty()) { + configDir = getHome() + "/.config"; + } return configDir; } @@ -452,13 +504,17 @@ std::vector getConfigDirs() { Path getDataDir() { Path dataDir = getEnv("XDG_DATA_HOME"); - if (dataDir.empty()) dataDir = getHome() + "/.local/share"; + if (dataDir.empty()) { + dataDir = getHome() + "/.local/share"; + } return dataDir; } Paths createDirs(const Path& path) { Paths created; - if (path == "/") return created; + if (path == "/") { + return created; + } struct stat st; if (lstat(path.c_str(), &st) == -1) { @@ -491,7 +547,9 @@ void replaceSymlink(const Path& target, const Path& link) { try { createSymlink(target, tmp); } catch (SysError& e) { - if (e.errNo == EEXIST) continue; + if (e.errNo == EEXIST) { + continue; + } throw; } @@ -507,10 +565,14 @@ void readFull(int fd, unsigned char* buf, size_t count) { checkInterrupt(); ssize_t res = read(fd, (char*)buf, count); if (res == -1) { - if (errno == EINTR) continue; + if (errno == EINTR) { + continue; + } throw SysError("reading from file"); } - if (res == 0) throw EndOfFile("unexpected end-of-file"); + if (res == 0) { + throw EndOfFile("unexpected end-of-file"); + } count -= res; buf += res; } @@ -519,9 +581,13 @@ void readFull(int fd, unsigned char* buf, size_t count) { void writeFull(int fd, const unsigned char* buf, size_t count, bool allowInterrupts) { while (count) { - if (allowInterrupts) checkInterrupt(); + if (allowInterrupts) { + checkInterrupt(); + } ssize_t res = write(fd, (char*)buf, count); - if (res == -1 && errno != EINTR) throw SysError("writing to file"); + if (res == -1 && errno != EINTR) { + throw SysError("writing to file"); + } if (res > 0) { count -= res; buf += res; @@ -560,8 +626,12 @@ void drainFD(int fd, Sink& sink, bool block) { checkInterrupt(); ssize_t rd = read(fd, buf.data(), buf.size()); if (rd == -1) { - if (!block && (errno == EAGAIN || errno == EWOULDBLOCK)) break; - if (errno != EINTR) throw SysError("reading from file"); + if (!block && (errno == EAGAIN || errno == EWOULDBLOCK)) { + break; + } + if (errno != EINTR) { + throw SysError("reading from file"); + } } else if (rd == 0) break; else @@ -644,9 +714,13 @@ int AutoCloseFD::release() { void Pipe::create() { int fds[2]; #if HAVE_PIPE2 - if (pipe2(fds, O_CLOEXEC) != 0) throw SysError("creating pipe"); + if (pipe2(fds, O_CLOEXEC) != 0) { + throw SysError("creating pipe"); + } #else - if (pipe(fds) != 0) throw SysError("creating pipe"); + if (pipe(fds) != 0) { + throw SysError("creating pipe"); + } closeOnExec(fds[0]); closeOnExec(fds[1]); #endif @@ -661,11 +735,15 @@ Pid::Pid() {} Pid::Pid(pid_t pid) : pid(pid) {} Pid::~Pid() { - if (pid != -1) kill(); + if (pid != -1) { + kill(); + } } void Pid::operator=(pid_t pid) { - if (this->pid != -1 && this->pid != pid) kill(); + if (this->pid != -1 && this->pid != pid) { + kill(); + } this->pid = pid; killSignal = SIGKILL; // reset signal to default } @@ -744,11 +822,17 @@ void killUser(uid_t uid) { calling process. In the OSX libc, it's set to true, which means "follow POSIX", which we don't want here */ - if (syscall(SYS_kill, -1, SIGKILL, false) == 0) break; + if (syscall(SYS_kill, -1, SIGKILL, false) == 0) { + break; + } #else - if (kill(-1, SIGKILL) == 0) break; + if (kill(-1, SIGKILL) == 0) { + break; + } #endif - if (errno == ESRCH) break; /* no more processes */ + if (errno == ESRCH) { + break; + } /* no more processes */ if (errno != EINTR) throw SysError(format("cannot kill processes for uid '%1%'") % uid); } @@ -780,7 +864,9 @@ static pid_t doFork(bool allowVfork, std::function fun) { #else pid_t pid = fork(); #endif - if (pid != 0) return pid; + if (pid != 0) { + return pid; + } fun(); abort(); } @@ -808,7 +894,9 @@ pid_t startProcess(std::function fun, const ProcessOptions& options) { }; pid_t pid = doFork(options.allowVfork, wrapper); - if (pid == -1) throw SysError("unable to fork"); + if (pid == -1) { + throw SysError("unable to fork"); + } return pid; } @@ -866,19 +954,27 @@ void runProgram2(const RunOptions& options) { /* Create a pipe. */ Pipe out, in; - if (options.standardOut) out.create(); - if (source) in.create(); + if (options.standardOut) { + out.create(); + } + if (source) { + in.create(); + } ProcessOptions processOptions; // vfork implies that the environment of the main process and the fork will // be shared (technically this is undefined, but in practice that's the // case), so we can't use it if we alter the environment - if (options.environment) processOptions.allowVfork = false; + if (options.environment) { + processOptions.allowVfork = false; + } /* Fork. */ Pid pid = startProcess( [&]() { - if (options.environment) replaceEnv(*options.environment); + if (options.environment) { + replaceEnv(*options.environment); + } if (options.standardOut && dup2(out.writeSide.get(), STDOUT_FILENO) == -1) throw SysError("dupping stdout"); @@ -919,7 +1015,9 @@ void runProgram2(const RunOptions& options) { std::promise promise; Finally doJoin([&]() { - if (writerThread.joinable()) writerThread.join(); + if (writerThread.joinable()) { + writerThread.join(); + } }); if (source) { @@ -944,13 +1042,17 @@ void runProgram2(const RunOptions& options) { }); } - if (options.standardOut) drainFD(out.readSide.get(), *options.standardOut); + if (options.standardOut) { + drainFD(out.readSide.get(), *options.standardOut); + } /* Wait for the child to finish. */ int status = pid.wait(); /* Wait for the writer thread to finish. */ - if (source) promise.get_future().get(); + if (source) { + promise.get_future().get(); + } if (status) throw ExecError(status, fmt("program '%1%' %2%", options.program, @@ -975,7 +1077,9 @@ void closeMostFDs(const set& exceptions) { int maxFD = 0; maxFD = sysconf(_SC_OPEN_MAX); for (int fd = 0; fd < maxFD; ++fd) - if (!exceptions.count(fd)) close(fd); /* ignore result */ + if (!exceptions.count(fd)) { + close(fd); + } /* ignore result */ } void closeOnExec(int fd) { @@ -1012,7 +1116,9 @@ C tokenizeString(const string& s, const string& separators) { string::size_type pos = s.find_first_not_of(separators, 0); while (pos != string::npos) { string::size_type end = s.find_first_of(separators, pos + 1); - if (end == string::npos) end = s.size(); + if (end == string::npos) { + end = s.size(); + } string token(s, pos, end - pos); result.insert(result.end(), token); pos = s.find_first_not_of(separators, end); @@ -1028,7 +1134,9 @@ template vector tokenizeString(const string& s, string concatStringsSep(const string& sep, const Strings& ss) { string s; for (auto& i : ss) { - if (s.size() != 0) s += sep; + if (s.size() != 0) { + s += sep; + } s += i; } return s; @@ -1037,7 +1145,9 @@ string concatStringsSep(const string& sep, const Strings& ss) { string concatStringsSep(const string& sep, const StringSet& ss) { string s; for (auto& i : ss) { - if (s.size() != 0) s += sep; + if (s.size() != 0) { + s += sep; + } s += i; } return s; @@ -1050,14 +1160,18 @@ string chomp(const string& s) { string trim(const string& s, const string& whitespace) { auto i = s.find_first_not_of(whitespace); - if (i == string::npos) return ""; + if (i == string::npos) { + return ""; + } auto j = s.find_last_not_of(whitespace); return string(s, i, j == string::npos ? j : j - i + 1); } string replaceStrings(const std::string& s, const std::string& from, const std::string& to) { - if (from.empty()) return s; + if (from.empty()) { + return s; + } string res = s; size_t pos = 0; while ((pos = res.find(from, pos)) != std::string::npos) { @@ -1143,12 +1257,18 @@ std::string filterANSIEscapes(const std::string& s, bool filterAll, // eat intermediate bytes while (i != s.end() && *i >= 0x20 && *i <= 0x2f) e += *i++; // eat final byte - if (i != s.end() && *i >= 0x40 && *i <= 0x7e) e += last = *i++; + if (i != s.end() && *i >= 0x40 && *i <= 0x7e) { + e += last = *i++; + } } else { - if (i != s.end() && *i >= 0x40 && *i <= 0x5f) e += *i++; + if (i != s.end() && *i >= 0x40 && *i <= 0x5f) { + e += *i++; + } } - if (!filterAll && last == 'm') t += e; + if (!filterAll && last == 'm') { + t += e; + } } else if (*i == '\t') { @@ -1190,7 +1310,9 @@ string base64Encode(const string& s) { } } - if (nbits) res.push_back(base64Chars[data << (6 - nbits) & 0x3f]); + if (nbits) { + res.push_back(base64Chars[data << (6 - nbits) & 0x3f]); + } while (res.size() % 4) res.push_back('='); return res; @@ -1212,11 +1334,17 @@ string base64Decode(const string& s) { unsigned int d = 0, bits = 0; for (char c : s) { - if (c == '=') break; - if (c == '\n') continue; + if (c == '=') { + break; + } + if (c == '\n') { + continue; + } char digit = decode[(unsigned char)c]; - if (digit == -1) throw Error("invalid character in Base64 string"); + if (digit == -1) { + throw Error("invalid character in Base64 string"); + } bits += 6; d = d << 6 | digit; diff --git a/third_party/nix/src/libutil/util.hh b/third_party/nix/src/libutil/util.hh index 3ebe18f54837..a7e9b20fd560 100644 --- a/third_party/nix/src/libutil/util.hh +++ b/third_party/nix/src/libutil/util.hh @@ -416,7 +416,9 @@ class Callback { Callback(Callback&& callback) : fun(std::move(callback.fun)) { auto prev = callback.done.test_and_set(); - if (prev) done.test_and_set(); + if (prev) { + done.test_and_set(); + } } void operator()(T&& t) noexcept { diff --git a/third_party/nix/src/libutil/xml-writer.cc b/third_party/nix/src/libutil/xml-writer.cc index 8bc4e187779f..e07dd92f021e 100644 --- a/third_party/nix/src/libutil/xml-writer.cc +++ b/third_party/nix/src/libutil/xml-writer.cc @@ -33,7 +33,9 @@ void XMLWriter::openElement(const string& name, const XMLAttrs& attrs) { output << "<" << name; writeAttrs(attrs); output << ">"; - if (indent) output << std::endl; + if (indent) { + output << std::endl; + } pendingElems.push_back(name); } @@ -41,9 +43,13 @@ void XMLWriter::closeElement() { assert(!pendingElems.empty()); indent_(pendingElems.size() - 1); output << ""; - if (indent) output << std::endl; + if (indent) { + output << std::endl; + } pendingElems.pop_back(); - if (pendingElems.empty()) closed = true; + if (pendingElems.empty()) { + closed = true; + } } void XMLWriter::writeEmptyElement(const string& name, const XMLAttrs& attrs) { @@ -52,7 +58,9 @@ void XMLWriter::writeEmptyElement(const string& name, const XMLAttrs& attrs) { output << "<" << name; writeAttrs(attrs); output << " />"; - if (indent) output << std::endl; + if (indent) { + output << std::endl; + } } void XMLWriter::writeAttrs(const XMLAttrs& attrs) { -- cgit 1.4.1