refactor(3p/nix/libutil): Replace hasPrefix/Suffix with Abseil

Uses the equivalent absl::StartsWith and absl::EndsWith functions
instead.
This commit is contained in:
Vincent Ambo 2020-05-25 02:19:01 +01:00
parent 8cf1322a6f
commit b99b368d17
21 changed files with 69 additions and 57 deletions

View file

@ -7,6 +7,7 @@
#include <tuple>
#include <absl/strings/ascii.h>
#include <absl/strings/match.h>
#include <absl/strings/str_cat.h>
#include <glog/logging.h>
@ -188,7 +189,7 @@ static int _main(int argc, char* argv[]) {
DLOG(INFO) << "connecting to '" << bestMachine->storeUri << "'";
Store::Params storeParams;
if (hasPrefix(bestMachine->storeUri, "ssh://")) {
if (absl::StartsWith(bestMachine->storeUri, "ssh://")) {
storeParams["max-connections"] = "1";
storeParams["log-fd"] = "4";
if (!bestMachine->sshKey.empty()) {

View file

@ -7,6 +7,7 @@
#include <iostream>
#include <new>
#include <absl/strings/match.h>
#include <gc/gc.h>
#include <gc/gc_cpp.h>
#include <glog/logging.h>
@ -423,7 +424,7 @@ void EvalState::checkURI(const std::string& uri) {
for (auto& prefix : evalSettings.allowedUris.get()) {
if (uri == prefix ||
(uri.size() > prefix.size() && !prefix.empty() &&
hasPrefix(uri, prefix) &&
absl::StartsWith(uri, prefix) &&
(prefix[prefix.size() - 1] == '/' || uri[prefix.size()] == '/'))) {
return;
}
@ -431,12 +432,12 @@ void EvalState::checkURI(const std::string& uri) {
/* If the URI is a path, then check it against allowedPaths as
well. */
if (hasPrefix(uri, "/")) {
if (absl::StartsWith(uri, "/")) {
checkSourcePath(uri);
return;
}
if (hasPrefix(uri, "file://")) {
if (absl::StartsWith(uri, "file://")) {
checkSourcePath(std::string(uri, 7));
return;
}

View file

@ -2,6 +2,7 @@
#include <regex>
#include <absl/strings/ascii.h>
#include <absl/strings/match.h>
#include <glog/logging.h>
#include <sys/time.h>
@ -31,7 +32,8 @@ GitInfo exportGit(ref<Store> store, const std::string& uri,
if (evalSettings.pureEval && rev == "")
throw Error("in pure evaluation mode, 'fetchGit' requires a Git revision");
if (!ref && rev == "" && hasPrefix(uri, "/") && pathExists(uri + "/.git")) {
if (!ref && rev == "" && absl::StartsWith(uri, "/") &&
pathExists(uri + "/.git")) {
bool clean = true;
try {
@ -56,7 +58,7 @@ GitInfo exportGit(ref<Store> store, const std::string& uri,
runProgram("git", true, {"-C", uri, "ls-files", "-z"}), "\0"s);
PathFilter filter = [&](const Path& p) -> bool {
assert(hasPrefix(p, uri));
assert(absl::StartsWith(p, uri));
std::string file(p, uri.size() + 1);
auto st = lstat(p);
@ -64,7 +66,7 @@ GitInfo exportGit(ref<Store> store, const std::string& uri,
if (S_ISDIR(st.st_mode)) {
auto prefix = file + "/";
auto i = files.lower_bound(prefix);
return i != files.end() && hasPrefix(*i, prefix);
return i != files.end() && absl::StartsWith(*i, prefix);
}
return files.count(file);

View file

@ -2,6 +2,7 @@
#include <regex>
#include <absl/strings/ascii.h>
#include <absl/strings/match.h>
#include <glog/logging.h>
#include <sys/time.h>
@ -31,7 +32,7 @@ HgInfo exportMercurial(ref<Store> store, const std::string& uri,
"in pure evaluation mode, 'fetchMercurial' requires a Mercurial "
"revision");
if (rev == "" && hasPrefix(uri, "/") && pathExists(uri + "/.hg")) {
if (rev == "" && absl::StartsWith(uri, "/") && pathExists(uri + "/.hg")) {
bool clean = runProgram("hg", true,
{"status", "-R", uri, "--modified", "--added",
"--removed"}) == "";
@ -54,7 +55,7 @@ HgInfo exportMercurial(ref<Store> store, const std::string& uri,
"\0"s);
PathFilter filter = [&](const Path& p) -> bool {
assert(hasPrefix(p, uri));
assert(absl::StartsWith(p, uri));
std::string file(p, uri.size() + 1);
auto st = lstat(p);
@ -62,7 +63,7 @@ HgInfo exportMercurial(ref<Store> store, const std::string& uri,
if (S_ISDIR(st.st_mode)) {
auto prefix = file + "/";
auto i = files.lower_bound(prefix);
return i != files.end() && hasPrefix(*i, prefix);
return i != files.end() && absl::StartsWith(*i, prefix);
}
return files.count(file);

View file

@ -1,5 +1,6 @@
#include <algorithm>
#include <absl/strings/match.h>
#include <fcntl.h>
#include <glog/logging.h>
#include <sys/stat.h>
@ -56,10 +57,10 @@ static void createLinks(const Path& srcDir, const Path& dstDir, int priority) {
* Python package brings its own
* `$out/lib/pythonX.Y/site-packages/easy-install.pth'.)
*/
if (hasSuffix(srcFile, "/propagated-build-inputs") ||
hasSuffix(srcFile, "/nix-support") ||
hasSuffix(srcFile, "/perllocal.pod") ||
hasSuffix(srcFile, "/info/dir") || hasSuffix(srcFile, "/log"))
if (absl::EndsWith(srcFile, "/propagated-build-inputs") ||
absl::EndsWith(srcFile, "/nix-support") ||
absl::EndsWith(srcFile, "/perllocal.pod") ||
absl::EndsWith(srcFile, "/info/dir") || absl::EndsWith(srcFile, "/log"))
continue;
else if (S_ISDIR(srcSt.st_mode)) {

View file

@ -1,3 +1,4 @@
#include <absl/strings/match.h>
#include <glog/logging.h>
#include "archive.hh"
@ -41,7 +42,7 @@ void builtinFetchurl(const BasicDerivation& drv, const std::string& netrcData) {
request.decompress = false;
auto decompressor = makeDecompressionSink(
unpack && hasSuffix(mainUrl, ".xz") ? "xz" : "none", sink);
unpack && absl::EndsWith(mainUrl, ".xz") ? "xz" : "none", sink);
downloader->download(std::move(request), *decompressor);
decompressor->finish();
});
@ -61,7 +62,7 @@ void builtinFetchurl(const BasicDerivation& drv, const std::string& netrcData) {
/* Try the hashed mirrors first. */
if (getAttr("outputHashMode") == "flat")
for (auto hashedMirror : settings.hashedMirrors.get()) try {
if (!hasSuffix(hashedMirror, "/")) {
if (!absl::EndsWith(hashedMirror, "/")) {
hashedMirror += '/';
}
auto ht = parseHashType(getAttr("outputHashAlgo"));

View file

@ -1,5 +1,7 @@
#include "derivations.hh"
#include <absl/strings/match.h>
#include "fs-accessor.hh"
#include "globals.hh"
#include "istringstream_nocopy.hh"
@ -299,7 +301,7 @@ std::string Derivation::unparse() const {
}
bool isDerivation(const std::string& fileName) {
return hasSuffix(fileName, drvExtension);
return absl::EndsWith(fileName, drvExtension);
}
bool BasicDerivation::isFixedOutput() const {

View file

@ -1,6 +1,7 @@
#include "download.hh"
#include <absl/strings/ascii.h>
#include <absl/strings/match.h>
#include <absl/strings/numbers.h>
#include "archive.hh"
@ -653,8 +654,8 @@ struct CurlDownloader : public Downloader {
}
void enqueueItem(const std::shared_ptr<DownloadItem>& item) {
if (item->request.data && !hasPrefix(item->request.uri, "http://") &&
!hasPrefix(item->request.uri, "https://")) {
if (item->request.data && !absl::StartsWith(item->request.uri, "http://") &&
!absl::StartsWith(item->request.uri, "https://")) {
throw nix::Error("uploading to '%s' is not supported", item->request.uri);
}
@ -690,7 +691,7 @@ struct CurlDownloader : public Downloader {
void enqueueDownload(const DownloadRequest& request,
Callback<DownloadResult> callback) override {
/* Ugly hack to support s3:// URIs. */
if (hasPrefix(request.uri, "s3://")) {
if (absl::StartsWith(request.uri, "s3://")) {
// FIXME: do this on a worker thread
try {
#ifdef ENABLE_S3

View file

@ -6,6 +6,7 @@
#include <random>
#include <regex>
#include <absl/strings/match.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
@ -512,7 +513,7 @@ struct LocalStore::GCState {
bool LocalStore::isActiveTempFile(const GCState& state, const Path& path,
const std::string& suffix) {
return hasSuffix(path, suffix) &&
return absl::EndsWith(path, suffix) &&
state.tempRoots.find(std::string(
path, 0, path.size() - suffix.size())) != state.tempRoots.end();
}

View file

@ -1,5 +1,7 @@
#include <utility>
#include <absl/strings/match.h>
#include "binary-cache-store.hh"
#include "globals.hh"
#include "nar-info-disk-cache.hh"
@ -39,7 +41,7 @@ class LocalBinaryCacheStore : public BinaryCacheStore {
PathSet paths;
for (auto& entry : readDirectory(binaryCacheDir)) {
if (entry.name.size() != 40 || !hasSuffix(entry.name, ".narinfo")) {
if (entry.name.size() != 40 || !absl::EndsWith(entry.name, ".narinfo")) {
continue;
}
paths.insert(storeDir + "/" +

View file

@ -3,6 +3,7 @@
#include <algorithm>
#include <absl/strings/ascii.h>
#include <absl/strings/match.h>
#include <absl/strings/string_view.h>
#include <glog/logging.h>
@ -21,9 +22,10 @@ Machine::Machine(decltype(storeUri)& storeUri,
// Backwards compatibility: if the URI is a hostname,
// prepend ssh://.
storeUri.find("://") != std::string::npos ||
hasPrefix(storeUri, "local") ||
hasPrefix(storeUri, "remote") ||
hasPrefix(storeUri, "auto") || hasPrefix(storeUri, "/")
absl::StartsWith(storeUri, "local") ||
absl::StartsWith(storeUri, "remote") ||
absl::StartsWith(storeUri, "auto") ||
absl::StartsWith(storeUri, "/")
? storeUri
: "ssh://" + storeUri),
systemTypes(systemTypes),

View file

@ -3,6 +3,7 @@
#include "s3-binary-cache-store.hh"
#include <absl/strings/ascii.h>
#include <absl/strings/match.h>
#include <aws/core/Aws.h>
#include <aws/core/VersionConfig.h>
#include <aws/core/auth/AWSCredentialsProvider.h>
@ -347,12 +348,12 @@ struct S3BinaryCacheStoreImpl : public S3BinaryCacheStore {
void upsertFile(const std::string& path, const std::string& data,
const std::string& mimeType) override {
if (narinfoCompression != "" && hasSuffix(path, ".narinfo"))
if (narinfoCompression != "" && absl::EndsWith(path, ".narinfo"))
uploadFile(path, *compress(narinfoCompression, data), mimeType,
narinfoCompression);
else if (lsCompression != "" && hasSuffix(path, ".ls"))
else if (lsCompression != "" && absl::EndsWith(path, ".ls"))
uploadFile(path, *compress(lsCompression, data), mimeType, lsCompression);
else if (logCompression != "" && hasPrefix(path, "log/"))
else if (logCompression != "" && absl::StartsWith(path, "log/"))
uploadFile(path, *compress(logCompression, data), mimeType,
logCompression);
else
@ -400,7 +401,7 @@ struct S3BinaryCacheStoreImpl : public S3BinaryCacheStore {
for (auto object : contents) {
auto& key = object.GetKey();
if (key.size() != 40 || !hasSuffix(key, ".narinfo")) {
if (key.size() != 40 || !absl::EndsWith(key, ".narinfo")) {
continue;
}
paths.insert(storeDir + "/" + key.substr(0, key.size() - 8));

View file

@ -2,6 +2,8 @@
#include <utility>
#include <absl/strings/match.h>
namespace nix {
SSHMaster::SSHMaster(const std::string& host, std::string keyFile,
@ -12,7 +14,7 @@ SSHMaster::SSHMaster(const std::string& host, std::string keyFile,
useMaster(useMaster && !fakeSSH),
compress(compress),
logFD(logFD) {
if (host.empty() || hasPrefix(host, "-")) {
if (host.empty() || absl::StartsWith(host, "-")) {
throw Error("invalid SSH host name '%s'", host);
}
}

View file

@ -3,6 +3,7 @@
#include <future>
#include <utility>
#include <absl/strings/match.h>
#include <absl/strings/numbers.h>
#include <glog/logging.h>
@ -771,7 +772,7 @@ bool ValidPathInfo::isContentAddressed(const Store& store) const {
<< "' claims to be content-addressed but isn't";
};
if (hasPrefix(ca, "text:")) {
if (absl::StartsWith(ca, "text:")) {
Hash hash(std::string(ca, 5));
if (store.makeTextPath(storePathToName(path), hash, references) == path) {
return true;
@ -780,7 +781,7 @@ bool ValidPathInfo::isContentAddressed(const Store& store) const {
}
else if (hasPrefix(ca, "fixed:")) {
else if (absl::StartsWith(ca, "fixed:")) {
bool recursive = ca.compare(6, 2, "r:") == 0;
Hash hash(std::string(ca, recursive ? 8 : 6));
if (references.empty() &&
@ -906,7 +907,7 @@ StoreType getStoreType(const std::string& uri, const std::string& stateDir) {
if (uri == "daemon") {
return tDaemon;
}
if (uri == "local" || hasPrefix(uri, "/")) {
if (uri == "local" || absl::StartsWith(uri, "/")) {
return tLocal;
} else if (uri.empty() || uri == "auto") {
if (access(stateDir.c_str(), R_OK | W_OK) == 0) {
@ -930,7 +931,7 @@ static RegisterStoreImplementation regStore([](const std::string& uri,
return std::shared_ptr<Store>(std::make_shared<UDSRemoteStore>(params));
case tLocal: {
Store::Params params2 = params;
if (hasPrefix(uri, "/")) {
if (absl::StartsWith(uri, "/")) {
params2["root"] = uri;
}
return std::shared_ptr<Store>(std::make_shared<LocalStore>(params2));

View file

@ -1255,15 +1255,6 @@ bool statusOk(int status) {
return WIFEXITED(status) && WEXITSTATUS(status) == 0;
}
bool hasPrefix(const std::string& s, const std::string& prefix) {
return s.compare(0, prefix.size(), prefix) == 0;
}
bool hasSuffix(const std::string& s, const std::string& suffix) {
return s.size() >= suffix.size() &&
std::string(s, s.size() - suffix.size()) == suffix;
}
std::string toLower(const std::string& s) {
std::string r(s);
for (auto& c : r) {

View file

@ -344,12 +344,6 @@ bool string2Float(const std::string& s, N& n) {
return str && str.get() == EOF;
}
/* Return true iff `s' starts with `prefix'. */
bool hasPrefix(const std::string& s, const std::string& prefix);
/* Return true iff `s' ends in `suffix'. */
bool hasSuffix(const std::string& s, const std::string& suffix);
/* Convert a string to lower case. */
std::string toLower(const std::string& s);

View file

@ -4,6 +4,7 @@
#include <iostream>
#include <sstream>
#include <absl/strings/match.h>
#include <absl/strings/numbers.h>
#include <glog/logging.h>
#include <sys/stat.h>
@ -111,13 +112,13 @@ static void getAllExprs(EvalState& state, const Path& path, StringSet& attrs,
}
if (isNixExpr(path2, st) &&
(!S_ISREG(st.st_mode) || hasSuffix(path2, ".nix"))) {
(!S_ISREG(st.st_mode) || absl::EndsWith(path2, ".nix"))) {
/* Strip off the `.nix' filename suffix (if applicable),
otherwise the attribute cannot be selected with the
`-A' option. Useful if you want to stick a Nix
expression directly in ~/.nix-defexpr. */
std::string attrName = i;
if (hasSuffix(attrName, ".nix")) {
if (absl::EndsWith(attrName, ".nix")) {
attrName = std::string(attrName, 0, attrName.size() - 4);
}
if (attrs.find(attrName) != attrs.end()) {

View file

@ -1,5 +1,6 @@
#include <iostream>
#include <absl/strings/match.h>
#include <fcntl.h>
#include <glog/logging.h>
#include <sys/stat.h>
@ -51,7 +52,8 @@ std::string resolveMirrorUri(EvalState& state, std::string uri) {
std::string mirror =
state.forceString(*mirrorList->second.value->listElems()[0]);
return mirror + (hasSuffix(mirror, "/") ? "" : "/") + std::string(s, p + 1);
return mirror + (absl::EndsWith(mirror, "/") ? "" : "/") +
std::string(s, p + 1);
}
static int _main(int argc, char** argv) {
@ -203,7 +205,7 @@ static int _main(int argc, char** argv) {
LOG(INFO) << "unpacking...";
Path unpacked = (Path)tmpDir + "/unpacked";
createDirs(unpacked);
if (hasSuffix(baseNameOf(uri), ".zip")) {
if (absl::EndsWith(baseNameOf(uri), ".zip")) {
runProgram("unzip", true, {"-qq", tmpFile, "-d", unpacked});
} else {
// FIXME: this requires GNU tar for decompression.

View file

@ -1,3 +1,5 @@
#include <absl/strings/match.h>
#include "command.hh"
#include "serve-protocol.hh"
#include "shared.hh"
@ -73,7 +75,7 @@ struct CmdDoctor : StoreCommand {
Path userEnv = canonPath(profileDir, true);
if (store->isStorePath(userEnv) &&
hasSuffix(userEnv, "user-environment")) {
absl::EndsWith(userEnv, "user-environment")) {
while (profileDir.find("/profiles/") == std::string::npos &&
isLink(profileDir)) {
profileDir = absPath(readLink(profileDir), dirOf(profileDir));

View file

@ -6,6 +6,7 @@
#include <utility>
#include <absl/strings/ascii.h>
#include <absl/strings/match.h>
#include <glog/logging.h>
#ifdef READLINE
@ -356,7 +357,7 @@ StringSet NixRepl::completePrefix(const std::string& prefix) {
auto dir = std::string(cur, 0, slash);
auto prefix2 = std::string(cur, slash + 1);
for (auto& entry : readDirectory(dir.empty() ? "/" : dir)) {
if (entry.name[0] != '.' && hasPrefix(entry.name, prefix2)) {
if (entry.name[0] != '.' && absl::StartsWith(entry.name, prefix2)) {
completions.insert(prev + dir + "/" + entry.name);
}
}

View file

@ -1,3 +1,4 @@
#include <absl/strings/match.h>
#include <glog/logging.h>
#include "attr-path.hh"
@ -114,7 +115,7 @@ struct CmdUpgradeNix : MixDryRun, StoreCommand {
LOG(INFO) << "found Nix in '" << where << "'";
if (hasPrefix(where, "/run/current-system")) {
if (absl::StartsWith(where, "/run/current-system")) {
throw Error("Nix on NixOS must be upgraded via 'nixos-rebuild'");
}
@ -130,7 +131,8 @@ struct CmdUpgradeNix : MixDryRun, StoreCommand {
Path userEnv = canonPath(profileDir, true);
if (baseNameOf(where) != "bin" || !hasSuffix(userEnv, "user-environment")) {
if (baseNameOf(where) != "bin" ||
!absl::EndsWith(userEnv, "user-environment")) {
throw Error("directory '%s' does not appear to be part of a Nix profile",
where);
}