Rename two hash constructors to proper functions

This commit is contained in:
Carlo Nucera 2020-07-01 18:34:18 -04:00
parent c8c4bcf90e
commit 263ccdd489
20 changed files with 45 additions and 37 deletions

View file

@ -29,7 +29,7 @@ static void prim_fetchGit(EvalState & state, const Pos & pos, Value * * args, Va
else if (n == "ref") else if (n == "ref")
ref = state.forceStringNoCtx(*attr.value, *attr.pos); ref = state.forceStringNoCtx(*attr.value, *attr.pos);
else if (n == "rev") else if (n == "rev")
rev = Hash(state.forceStringNoCtx(*attr.value, *attr.pos), htSHA1); rev = Hash::parseAny(state.forceStringNoCtx(*attr.value, *attr.pos), htSHA1);
else if (n == "name") else if (n == "name")
name = state.forceStringNoCtx(*attr.value, *attr.pos); name = state.forceStringNoCtx(*attr.value, *attr.pos);
else if (n == "submodules") else if (n == "submodules")

View file

@ -31,7 +31,7 @@ static void prim_fetchMercurial(EvalState & state, const Pos & pos, Value * * ar
// be both a revision or a branch/tag name. // be both a revision or a branch/tag name.
auto value = state.forceStringNoCtx(*attr.value, *attr.pos); auto value = state.forceStringNoCtx(*attr.value, *attr.pos);
if (std::regex_match(value, revRegex)) if (std::regex_match(value, revRegex))
rev = Hash(value, htSHA1); rev = Hash::parseAny(value, htSHA1);
else else
ref = value; ref = value;
} }

View file

@ -225,14 +225,14 @@ struct GitInput : Input
if (isLocal) { if (isLocal) {
if (!input->rev) if (!input->rev)
input->rev = Hash(chomp(runProgram("git", true, { "-C", actualUrl, "rev-parse", *input->ref })), htSHA1); input->rev = Hash::parseAny(chomp(runProgram("git", true, { "-C", actualUrl, "rev-parse", *input->ref })), htSHA1);
repoDir = actualUrl; repoDir = actualUrl;
} else { } else {
if (auto res = getCache()->lookup(store, mutableAttrs)) { if (auto res = getCache()->lookup(store, mutableAttrs)) {
auto rev2 = Hash(getStrAttr(res->first, "rev"), htSHA1); auto rev2 = Hash::parseAny(getStrAttr(res->first, "rev"), htSHA1);
if (!rev || rev == rev2) { if (!rev || rev == rev2) {
input->rev = rev2; input->rev = rev2;
return makeResult(res->first, std::move(res->second)); return makeResult(res->first, std::move(res->second));
@ -301,7 +301,7 @@ struct GitInput : Input
} }
if (!input->rev) if (!input->rev)
input->rev = Hash(chomp(readFile(localRefFile)), htSHA1); input->rev = Hash::parseAny(chomp(readFile(localRefFile)), htSHA1);
} }
bool isShallow = chomp(runProgram("git", true, { "-C", repoDir, "rev-parse", "--is-shallow-repository" })) == "true"; bool isShallow = chomp(runProgram("git", true, { "-C", repoDir, "rev-parse", "--is-shallow-repository" })) == "true";
@ -426,7 +426,7 @@ struct GitInputScheme : InputScheme
input->ref = *ref; input->ref = *ref;
} }
if (auto rev = maybeGetStrAttr(attrs, "rev")) if (auto rev = maybeGetStrAttr(attrs, "rev"))
input->rev = Hash(*rev, htSHA1); input->rev = Hash::parseAny(*rev, htSHA1);
input->shallow = maybeGetBoolAttr(attrs, "shallow").value_or(false); input->shallow = maybeGetBoolAttr(attrs, "shallow").value_or(false);

View file

@ -76,7 +76,7 @@ struct GitHubInput : Input
readFile( readFile(
store->toRealPath( store->toRealPath(
downloadFile(store, url, "source", false).storePath))); downloadFile(store, url, "source", false).storePath)));
rev = Hash(std::string { json["sha"] }, htSHA1); rev = Hash::parseAny(std::string { json["sha"] }, htSHA1);
debug("HEAD revision for '%s' is %s", url, rev->gitRev()); debug("HEAD revision for '%s' is %s", url, rev->gitRev());
} }
@ -140,7 +140,7 @@ struct GitHubInputScheme : InputScheme
if (path.size() == 2) { if (path.size() == 2) {
} else if (path.size() == 3) { } else if (path.size() == 3) {
if (std::regex_match(path[2], revRegex)) if (std::regex_match(path[2], revRegex))
input->rev = Hash(path[2], htSHA1); input->rev = Hash::parseAny(path[2], htSHA1);
else if (std::regex_match(path[2], refRegex)) else if (std::regex_match(path[2], refRegex))
input->ref = path[2]; input->ref = path[2];
else else
@ -152,7 +152,7 @@ struct GitHubInputScheme : InputScheme
if (name == "rev") { if (name == "rev") {
if (input->rev) if (input->rev)
throw BadURL("GitHub URL '%s' contains multiple commit hashes", url.url); throw BadURL("GitHub URL '%s' contains multiple commit hashes", url.url);
input->rev = Hash(value, htSHA1); input->rev = Hash::parseAny(value, htSHA1);
} }
else if (name == "ref") { else if (name == "ref") {
if (!std::regex_match(value, refRegex)) if (!std::regex_match(value, refRegex))
@ -185,7 +185,7 @@ struct GitHubInputScheme : InputScheme
input->repo = getStrAttr(attrs, "repo"); input->repo = getStrAttr(attrs, "repo");
input->ref = maybeGetStrAttr(attrs, "ref"); input->ref = maybeGetStrAttr(attrs, "ref");
if (auto rev = maybeGetStrAttr(attrs, "rev")) if (auto rev = maybeGetStrAttr(attrs, "rev"))
input->rev = Hash(*rev, htSHA1); input->rev = Hash::parseAny(*rev, htSHA1);
return input; return input;
} }
}; };

View file

@ -167,7 +167,7 @@ struct MercurialInput : Input
}); });
if (auto res = getCache()->lookup(store, mutableAttrs)) { if (auto res = getCache()->lookup(store, mutableAttrs)) {
auto rev2 = Hash(getStrAttr(res->first, "rev"), htSHA1); auto rev2 = Hash::parseAny(getStrAttr(res->first, "rev"), htSHA1);
if (!rev || rev == rev2) { if (!rev || rev == rev2) {
input->rev = rev2; input->rev = rev2;
return makeResult(res->first, std::move(res->second)); return makeResult(res->first, std::move(res->second));
@ -210,7 +210,7 @@ struct MercurialInput : Input
runProgram("hg", true, { "log", "-R", cacheDir, "-r", revOrRef, "--template", "{node} {rev} {branch}" })); runProgram("hg", true, { "log", "-R", cacheDir, "-r", revOrRef, "--template", "{node} {rev} {branch}" }));
assert(tokens.size() == 3); assert(tokens.size() == 3);
input->rev = Hash(tokens[0], htSHA1); input->rev = Hash::parseAny(tokens[0], htSHA1);
auto revCount = std::stoull(tokens[1]); auto revCount = std::stoull(tokens[1]);
input->ref = tokens[2]; input->ref = tokens[2];
@ -293,7 +293,7 @@ struct MercurialInputScheme : InputScheme
input->ref = *ref; input->ref = *ref;
} }
if (auto rev = maybeGetStrAttr(attrs, "rev")) if (auto rev = maybeGetStrAttr(attrs, "rev"))
input->rev = Hash(*rev, htSHA1); input->rev = Hash::parseAny(*rev, htSHA1);
return input; return input;
} }
}; };

View file

@ -101,7 +101,7 @@ struct PathInputScheme : InputScheme
for (auto & [name, value] : url.query) for (auto & [name, value] : url.query)
if (name == "rev") if (name == "rev")
input->rev = Hash(value, htSHA1); input->rev = Hash::parseAny(value, htSHA1);
else if (name == "revCount") { else if (name == "revCount") {
uint64_t revCount; uint64_t revCount;
if (!string2Int(value, revCount)) if (!string2Int(value, revCount))
@ -129,7 +129,7 @@ struct PathInputScheme : InputScheme
for (auto & [name, value] : attrs) for (auto & [name, value] : attrs)
if (name == "rev") if (name == "rev")
input->rev = Hash(getStrAttr(attrs, "rev"), htSHA1); input->rev = Hash::parseAny(getStrAttr(attrs, "rev"), htSHA1);
else if (name == "revCount") else if (name == "revCount")
input->revCount = getIntAttr(attrs, "revCount"); input->revCount = getIntAttr(attrs, "revCount");
else if (name == "lastModified") else if (name == "lastModified")

View file

@ -68,7 +68,7 @@ ContentAddress parseContentAddress(std::string_view rawCa) {
throw Error("text content address hash should use %s, but instead uses %s", throw Error("text content address hash should use %s, but instead uses %s",
printHashType(htSHA256), printHashType(hashType)); printHashType(htSHA256), printHashType(hashType));
return TextHash { return TextHash {
.hash = Hash { rest, std::move(hashType) }, .hash = Hash::parseAny(rest, std::move(hashType)),
}; };
} else if (prefix == "fixed") { } else if (prefix == "fixed") {
// Parse method // Parse method
@ -80,7 +80,7 @@ ContentAddress parseContentAddress(std::string_view rawCa) {
HashType hashType = parseHashType_(); HashType hashType = parseHashType_();
return FixedOutputHash { return FixedOutputHash {
.method = method, .method = method,
.hash = Hash { rest, std::move(hashType) }, .hash = Hash::parseAny(rest, std::move(hashType)),
}; };
} else } else
throw UsageError("content address prefix \"%s\" is unrecognized. Recogonized prefixes are \"text\" or \"fixed\"", prefix); throw UsageError("content address prefix \"%s\" is unrecognized. Recogonized prefixes are \"text\" or \"fixed\"", prefix);

View file

@ -706,7 +706,7 @@ static void performOp(TunnelLogger * logger, ref<Store> store,
auto deriver = readString(from); auto deriver = readString(from);
if (deriver != "") if (deriver != "")
info.deriver = store->parseStorePath(deriver); info.deriver = store->parseStorePath(deriver);
info.narHash = Hash(readString(from), htSHA256); info.narHash = Hash::parseAny(readString(from), htSHA256);
info.references = readStorePaths<StorePathSet>(*store, from); info.references = readStorePaths<StorePathSet>(*store, from);
from >> info.registrationTime >> info.narSize >> info.ultimate; from >> info.registrationTime >> info.narSize >> info.ultimate;
info.sigs = readStrings<StringSet>(from); info.sigs = readStrings<StringSet>(from);

View file

@ -118,7 +118,7 @@ static DerivationOutput parseDerivationOutput(const Store & store, istringstream
const HashType hashType = parseHashType(hashAlgo); const HashType hashType = parseHashType(hashAlgo);
fsh = FixedOutputHash { fsh = FixedOutputHash {
.method = std::move(method), .method = std::move(method),
.hash = Hash(hash, hashType), .hash = Hash::parseAny(hash, hashType),
}; };
} }
@ -416,7 +416,7 @@ static DerivationOutput readDerivationOutput(Source & in, const Store & store)
auto hashType = parseHashType(hashAlgo); auto hashType = parseHashType(hashAlgo);
fsh = FixedOutputHash { fsh = FixedOutputHash {
.method = std::move(method), .method = std::move(method),
.hash = Hash(hash, hashType), .hash = Hash::parseAny(hash, hashType),
}; };
} }

View file

@ -113,7 +113,7 @@ struct LegacySSHStore : public Store
if (GET_PROTOCOL_MINOR(conn->remoteVersion) >= 4) { if (GET_PROTOCOL_MINOR(conn->remoteVersion) >= 4) {
auto s = readString(conn->from); auto s = readString(conn->from);
info->narHash = s.empty() ? std::optional<Hash>{} : Hash{s}; info->narHash = s.empty() ? std::optional<Hash>{} : Hash::parseAnyPrefixed(s);
info->ca = parseContentAddressOpt(readString(conn->from)); info->ca = parseContentAddressOpt(readString(conn->from));
info->sigs = readStrings<StringSet>(conn->from); info->sigs = readStrings<StringSet>(conn->from);
} }

View file

@ -647,7 +647,7 @@ void LocalStore::queryPathInfoUncached(const StorePath & path,
info->id = useQueryPathInfo.getInt(0); info->id = useQueryPathInfo.getInt(0);
try { try {
info->narHash = Hash(useQueryPathInfo.getStr(1)); info->narHash = Hash::parseAnyPrefixed(useQueryPathInfo.getStr(1));
} catch (BadHash & e) { } catch (BadHash & e) {
throw Error("in valid-path entry for '%s': %s", printStorePath(path), e.what()); throw Error("in valid-path entry for '%s': %s", printStorePath(path), e.what());
} }

View file

@ -193,9 +193,9 @@ public:
narInfo->url = queryNAR.getStr(2); narInfo->url = queryNAR.getStr(2);
narInfo->compression = queryNAR.getStr(3); narInfo->compression = queryNAR.getStr(3);
if (!queryNAR.isNull(4)) if (!queryNAR.isNull(4))
narInfo->fileHash = Hash(queryNAR.getStr(4)); narInfo->fileHash = Hash::parseAnyPrefixed(queryNAR.getStr(4));
narInfo->fileSize = queryNAR.getInt(5); narInfo->fileSize = queryNAR.getInt(5);
narInfo->narHash = Hash(queryNAR.getStr(6)); narInfo->narHash = Hash::parseAnyPrefixed(queryNAR.getStr(6));
narInfo->narSize = queryNAR.getInt(7); narInfo->narSize = queryNAR.getInt(7);
for (auto & r : tokenizeString<Strings>(queryNAR.getStr(8), " ")) for (auto & r : tokenizeString<Strings>(queryNAR.getStr(8), " "))
narInfo->references.insert(StorePath(r)); narInfo->references.insert(StorePath(r));

View file

@ -12,7 +12,7 @@ NarInfo::NarInfo(const Store & store, const std::string & s, const std::string &
auto parseHashField = [&](const string & s) { auto parseHashField = [&](const string & s) {
try { try {
return Hash(s); return Hash::parseAnyPrefixed(s);
} catch (BadHash &) { } catch (BadHash &) {
throw corrupt(); throw corrupt();
} }

View file

@ -375,7 +375,7 @@ void RemoteStore::queryPathInfoUncached(const StorePath & path,
info = std::make_shared<ValidPathInfo>(StorePath(path)); info = std::make_shared<ValidPathInfo>(StorePath(path));
auto deriver = readString(conn->from); auto deriver = readString(conn->from);
if (deriver != "") info->deriver = parseStorePath(deriver); if (deriver != "") info->deriver = parseStorePath(deriver);
info->narHash = Hash(readString(conn->from), htSHA256); info->narHash = Hash::parseAny(readString(conn->from), htSHA256);
info->references = readStorePaths<StorePathSet>(*this, conn->from); info->references = readStorePaths<StorePathSet>(*this, conn->from);
conn->from >> info->registrationTime >> info->narSize; conn->from >> info->registrationTime >> info->narSize;
if (GET_PROTOCOL_MINOR(conn->daemonVersion) >= 16) { if (GET_PROTOCOL_MINOR(conn->daemonVersion) >= 16) {

View file

@ -703,7 +703,7 @@ std::optional<ValidPathInfo> decodeValidPathInfo(const Store & store, std::istre
if (hashGiven) { if (hashGiven) {
string s; string s;
getline(str, s); getline(str, s);
info.narHash = Hash(s, htSHA256); info.narHash = Hash::parseAny(s, htSHA256);
getline(str, s); getline(str, s);
if (!string2Int(s, info.narSize)) throw Error("number expected"); if (!string2Int(s, info.narSize)) throw Error("number expected");
} }

View file

@ -144,7 +144,10 @@ Hash Hash::fromSRI(std::string_view original) {
return Hash(rest, std::make_pair(parsedType, true)); return Hash(rest, std::make_pair(parsedType, true));
} }
Hash::Hash(std::string_view s) : Hash(s, std::nullopt) {} Hash Hash::parseAnyPrefixed(std::string_view s)
{
return parseAny(s, std::nullopt);
}
static std::pair<HashType, bool> newFunction(std::string_view & original, std::optional<HashType> optType) static std::pair<HashType, bool> newFunction(std::string_view & original, std::optional<HashType> optType)
{ {
@ -181,8 +184,11 @@ static std::pair<HashType, bool> newFunction(std::string_view & original, std::o
} }
// mutates the string_view // mutates the string_view
Hash::Hash(std::string_view original, std::optional<HashType> optType) Hash Hash::parseAny(std::string_view original, std::optional<HashType> optType)
: Hash(original, newFunction(original, optType)) {} {
auto typeAndSRI = newFunction(original, optType);
return Hash(original, typeAndSRI);
}
Hash::Hash(std::string_view rest, std::pair<HashType, bool> typeAndSRI) Hash::Hash(std::string_view rest, std::pair<HashType, bool> typeAndSRI)
: Hash(typeAndSRI.first) : Hash(typeAndSRI.first)
@ -249,7 +255,7 @@ Hash newHashAllowEmpty(std::string hashStr, std::optional<HashType> ht)
warn("found empty hash, assuming '%s'", h.to_string(SRI, true)); warn("found empty hash, assuming '%s'", h.to_string(SRI, true));
return h; return h;
} else } else
return Hash(hashStr, ht); return Hash::parseAny(hashStr, ht);
} }

View file

@ -39,9 +39,11 @@ struct Hash
Subresource Integrity hash expression). If the 'type' argument Subresource Integrity hash expression). If the 'type' argument
is not present, then the hash type must be specified in the is not present, then the hash type must be specified in the
string. */ string. */
Hash(std::string_view s, std::optional<HashType> type); static Hash parseAny(std::string_view s, std::optional<HashType> type);
// hash type must be part of string // hash type must be part of string
Hash(std::string_view s); static Hash parseAnyPrefixed(std::string_view s);
// prefix parsed separately; non SRI hash
static Hash parseAnyUnprefixed(std::string_view s, HashType type);
static Hash fromSRI(std::string_view original); static Hash fromSRI(std::string_view original);

View file

@ -156,7 +156,7 @@ static int _main(int argc, char * * argv)
Hash hash(ht), expectedHash(ht); Hash hash(ht), expectedHash(ht);
std::optional<StorePath> storePath; std::optional<StorePath> storePath;
if (args.size() == 2) { if (args.size() == 2) {
expectedHash = Hash(args[1], ht); expectedHash = Hash::parseAny(args[1], ht);
const auto recursive = unpack ? FileIngestionMethod::Recursive : FileIngestionMethod::Flat; const auto recursive = unpack ? FileIngestionMethod::Recursive : FileIngestionMethod::Flat;
storePath = store->makeFixedOutputPath(recursive, expectedHash, name); storePath = store->makeFixedOutputPath(recursive, expectedHash, name);
if (store->isValidPath(*storePath)) if (store->isValidPath(*storePath))

View file

@ -208,7 +208,7 @@ static void opPrintFixedPath(Strings opFlags, Strings opArgs)
string hash = *i++; string hash = *i++;
string name = *i++; string name = *i++;
cout << fmt("%s\n", store->printStorePath(store->makeFixedOutputPath(recursive, Hash(hash, hashAlgo), name))); cout << fmt("%s\n", store->printStorePath(store->makeFixedOutputPath(recursive, Hash::parseAny(hash, hashAlgo), name)));
} }
@ -950,7 +950,7 @@ static void opServe(Strings opFlags, Strings opArgs)
auto deriver = readString(in); auto deriver = readString(in);
if (deriver != "") if (deriver != "")
info.deriver = store->parseStorePath(deriver); info.deriver = store->parseStorePath(deriver);
info.narHash = Hash(readString(in), htSHA256); info.narHash = Hash::parseAny(readString(in), htSHA256);
info.references = readStorePaths<StorePathSet>(*store, in); info.references = readStorePaths<StorePathSet>(*store, in);
in >> info.registrationTime >> info.narSize >> info.ultimate; in >> info.registrationTime >> info.narSize >> info.ultimate;
info.sigs = readStrings<StringSet>(in); info.sigs = readStrings<StringSet>(in);

View file

@ -103,7 +103,7 @@ struct CmdToBase : Command
void run() override void run() override
{ {
for (auto s : args) for (auto s : args)
logger->stdout(Hash(s, ht).to_string(base, base == SRI)); logger->stdout(Hash::parseAny(s, ht).to_string(base, base == SRI));
} }
}; };