diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/libexpr/common-eval-args.hh | 2 | ||||
-rw-r--r-- | src/libexpr/parser.y | 2 | ||||
-rw-r--r-- | src/libexpr/primops.cc | 46 | ||||
-rw-r--r-- | src/libexpr/primops/fetchMercurial.cc | 198 | ||||
-rw-r--r-- | src/libexpr/primops/fetchgit.cc | 52 | ||||
-rw-r--r-- | src/libexpr/primops/fetchgit.hh | 3 | ||||
-rw-r--r-- | src/libstore/download.cc | 2 | ||||
-rw-r--r-- | src/libstore/s3-binary-cache-store.cc | 4 | ||||
-rw-r--r-- | src/libutil/archive.cc | 2 | ||||
-rw-r--r-- | src/libutil/archive.hh | 7 | ||||
-rw-r--r-- | src/libutil/hash.hh | 2 | ||||
-rw-r--r-- | src/libutil/util.cc | 41 | ||||
-rw-r--r-- | src/libutil/util.hh | 23 |
13 files changed, 314 insertions, 70 deletions
diff --git a/src/libexpr/common-eval-args.hh b/src/libexpr/common-eval-args.hh index 09fa406b2..be7fda783 100644 --- a/src/libexpr/common-eval-args.hh +++ b/src/libexpr/common-eval-args.hh @@ -6,7 +6,7 @@ namespace nix { class Store; class EvalState; -struct Bindings; +class Bindings; struct MixEvalArgs : virtual Args { diff --git a/src/libexpr/parser.y b/src/libexpr/parser.y index eee315228..7e63dc89f 100644 --- a/src/libexpr/parser.y +++ b/src/libexpr/parser.y @@ -667,7 +667,7 @@ std::pair<bool, std::string> EvalState::resolveSearchPathElem(const SearchPathEl try { if (hasPrefix(elem.second, "git://") || hasSuffix(elem.second, ".git")) // FIXME: support specifying revision/branch - res = { true, exportGit(store, elem.second, "master").storePath }; + res = { true, exportGit(store, elem.second).storePath }; else res = { true, getDownloader()->downloadCached(store, elem.second, true) }; } catch (DownloadError & e) { diff --git a/src/libexpr/primops.cc b/src/libexpr/primops.cc index cd0dfbc03..e3b5dfb42 100644 --- a/src/libexpr/primops.cc +++ b/src/libexpr/primops.cc @@ -1009,22 +1009,21 @@ static void prim_toFile(EvalState & state, const Pos & pos, Value * * args, Valu } -struct FilterFromExpr : PathFilter +static void prim_filterSource(EvalState & state, const Pos & pos, Value * * args, Value & v) { - EvalState & state; - Value & filter; - Pos pos; + PathSet context; + Path path = state.coerceToPath(pos, *args[1], context); + if (!context.empty()) + throw EvalError(format("string '%1%' cannot refer to other paths, at %2%") % path % pos); - FilterFromExpr(EvalState & state, Value & filter, const Pos & pos) - : state(state), filter(filter), pos(pos) - { - } + state.forceValue(*args[0]); + if (args[0]->type != tLambda) + throw TypeError(format("first argument in call to 'filterSource' is not a function but %1%, at %2%") % showType(*args[0]) % pos); - bool operator () (const Path & path) - { - struct stat st; - if (lstat(path.c_str(), &st)) - throw SysError(format("getting attributes of path '%1%'") % path); + path = state.checkSourcePath(path); + + PathFilter filter = [&](const Path & path) { + auto st = lstat(path); /* Call the filter function. The first argument is the path, the second is a string indicating the type of the file. */ @@ -1032,7 +1031,7 @@ struct FilterFromExpr : PathFilter mkString(arg1, path); Value fun2; - state.callFunction(filter, arg1, fun2, noPos); + state.callFunction(*args[0], arg1, fun2, noPos); Value arg2; mkString(arg2, @@ -1045,24 +1044,7 @@ struct FilterFromExpr : PathFilter state.callFunction(fun2, arg2, res, noPos); return state.forceBool(res, pos); - } -}; - - -static void prim_filterSource(EvalState & state, const Pos & pos, Value * * args, Value & v) -{ - PathSet context; - Path path = state.coerceToPath(pos, *args[1], context); - if (!context.empty()) - throw EvalError(format("string '%1%' cannot refer to other paths, at %2%") % path % pos); - - state.forceValue(*args[0]); - if (args[0]->type != tLambda) - throw TypeError(format("first argument in call to 'filterSource' is not a function but %1%, at %2%") % showType(*args[0]) % pos); - - FilterFromExpr filter(state, *args[0], pos); - - path = state.checkSourcePath(path); + }; Path dstPath = settings.readOnlyMode ? state.store->computeStorePathForPath(path, true, htSHA256, filter).first diff --git a/src/libexpr/primops/fetchMercurial.cc b/src/libexpr/primops/fetchMercurial.cc new file mode 100644 index 000000000..f48d003fc --- /dev/null +++ b/src/libexpr/primops/fetchMercurial.cc @@ -0,0 +1,198 @@ +#include "primops.hh" +#include "eval-inline.hh" +#include "download.hh" +#include "store-api.hh" +#include "pathlocks.hh" + +#include <sys/time.h> + +#include <regex> + +#include <nlohmann/json.hpp> + +using namespace std::string_literals; + +namespace nix { + +struct HgInfo +{ + Path storePath; + std::string branch; + std::string rev; + uint64_t revCount = 0; +}; + +std::regex commitHashRegex("^[0-9a-fA-F]{40}$"); + +HgInfo exportMercurial(ref<Store> store, const std::string & uri, + std::string rev, const std::string & name) +{ + if (rev == "" && hasPrefix(uri, "/") && pathExists(uri + "/.hg")) { + + bool clean = runProgram("hg", true, { "status", "-R", uri, "--modified", "--added", "--removed" }) == ""; + + if (!clean) { + + /* This is an unclean working tree. So copy all tracked + files. */ + + printTalkative("copying unclean Mercurial working tree '%s'", uri); + + HgInfo hgInfo; + hgInfo.rev = "0000000000000000000000000000000000000000"; + hgInfo.branch = chomp(runProgram("hg", true, { "branch", "-R", uri })); + + auto files = tokenizeString<std::set<std::string>>( + runProgram("hg", true, { "status", "-R", uri, "--clean", "--modified", "--added", "--no-status", "--print0" }), "\0"s); + + PathFilter filter = [&](const Path & p) -> bool { + assert(hasPrefix(p, uri)); + auto st = lstat(p); + std::string file(p, uri.size() + 1); + if (file == ".hg") return false; + // FIXME: filter out directories with no tracked files. + if (S_ISDIR(st.st_mode)) return true; + return files.count(file); + }; + + hgInfo.storePath = store->addToStore("source", uri, true, htSHA256, filter); + + return hgInfo; + } + } + + if (rev == "") rev = "default"; + + Path cacheDir = fmt("%s/nix/hg/%s", getCacheDir(), hashString(htSHA256, uri).to_string(Base32, false)); + + Path stampFile = fmt("%s/.hg/%s.stamp", cacheDir, hashString(htSHA512, rev).to_string(Base32, false)); + + /* If we haven't pulled this repo less than ‘tarball-ttl’ seconds, + do so now. */ + time_t now = time(0); + struct stat st; + if (stat(stampFile.c_str(), &st) != 0 || + st.st_mtime < now - settings.tarballTtl) + { + /* Except that if this is a commit hash that we already have, + we don't have to pull again. */ + if (!(std::regex_match(rev, commitHashRegex) + && pathExists(cacheDir) + && runProgram( + RunOptions("hg", { "log", "-R", cacheDir, "-r", rev, "--template", "1" }) + .killStderr(true)).second == "1")) + { + Activity act(*logger, lvlTalkative, actUnknown, fmt("fetching Mercurial repository '%s'", uri)); + + if (pathExists(cacheDir)) { + runProgram("hg", true, { "pull", "-R", cacheDir, "--", uri }); + } else { + createDirs(dirOf(cacheDir)); + runProgram("hg", true, { "clone", "--noupdate", "--", uri, cacheDir }); + } + } + + writeFile(stampFile, ""); + } + + auto tokens = tokenizeString<std::vector<std::string>>( + runProgram("hg", true, { "log", "-R", cacheDir, "-r", rev, "--template", "{node} {rev} {branch}" })); + assert(tokens.size() == 3); + + HgInfo hgInfo; + hgInfo.rev = tokens[0]; + hgInfo.revCount = std::stoull(tokens[1]); + hgInfo.branch = tokens[2]; + + std::string storeLinkName = hashString(htSHA512, name + std::string("\0"s) + hgInfo.rev).to_string(Base32, false); + Path storeLink = fmt("%s/.hg/%s.link", cacheDir, storeLinkName); + + try { + auto json = nlohmann::json::parse(readFile(storeLink)); + + assert(json["name"] == name && json["rev"] == hgInfo.rev); + + hgInfo.storePath = json["storePath"]; + + if (store->isValidPath(hgInfo.storePath)) { + printTalkative("using cached Mercurial store path '%s'", hgInfo.storePath); + return hgInfo; + } + + } catch (SysError & e) { + if (e.errNo != ENOENT) throw; + } + + Path tmpDir = createTempDir(); + AutoDelete delTmpDir(tmpDir, true); + + runProgram("hg", true, { "archive", "-R", cacheDir, "-r", rev, tmpDir }); + + deletePath(tmpDir + "/.hg_archival.txt"); + + hgInfo.storePath = store->addToStore(name, tmpDir); + + nlohmann::json json; + json["storePath"] = hgInfo.storePath; + json["uri"] = uri; + json["name"] = name; + json["branch"] = hgInfo.branch; + json["rev"] = hgInfo.rev; + json["revCount"] = hgInfo.revCount; + + writeFile(storeLink, json.dump()); + + return hgInfo; +} + +static void prim_fetchMercurial(EvalState & state, const Pos & pos, Value * * args, Value & v) +{ + std::string url; + std::string rev; + std::string name = "source"; + PathSet context; + + state.forceValue(*args[0]); + + if (args[0]->type == tAttrs) { + + state.forceAttrs(*args[0], pos); + + for (auto & attr : *args[0]->attrs) { + string n(attr.name); + if (n == "url") + url = state.coerceToString(*attr.pos, *attr.value, context, false, false); + else if (n == "rev") + rev = state.forceStringNoCtx(*attr.value, *attr.pos); + else if (n == "name") + name = state.forceStringNoCtx(*attr.value, *attr.pos); + else + throw EvalError("unsupported argument '%s' to 'fetchMercurial', at %s", attr.name, *attr.pos); + } + + if (url.empty()) + throw EvalError(format("'url' argument required, at %1%") % pos); + + } else + url = state.coerceToString(pos, *args[0], context, false, false); + + if (!isUri(url)) url = absPath(url); + + // FIXME: git externals probably can be used to bypass the URI + // whitelist. Ah well. + state.checkURI(url); + + auto hgInfo = exportMercurial(state.store, url, rev, name); + + state.mkAttrs(v, 8); + mkString(*state.allocAttr(v, state.sOutPath), hgInfo.storePath, PathSet({hgInfo.storePath})); + mkString(*state.allocAttr(v, state.symbols.create("branch")), hgInfo.branch); + mkString(*state.allocAttr(v, state.symbols.create("rev")), hgInfo.rev); + mkString(*state.allocAttr(v, state.symbols.create("shortRev")), std::string(hgInfo.rev, 0, 12)); + mkInt(*state.allocAttr(v, state.symbols.create("revCount")), hgInfo.revCount); + v.attrs->sort(); +} + +static RegisterPrimOp r("fetchMercurial", 1, prim_fetchMercurial); + +} diff --git a/src/libexpr/primops/fetchgit.cc b/src/libexpr/primops/fetchgit.cc index 4af530124..4b5ead320 100644 --- a/src/libexpr/primops/fetchgit.cc +++ b/src/libexpr/primops/fetchgit.cc @@ -16,9 +16,48 @@ using namespace std::string_literals; namespace nix { GitInfo exportGit(ref<Store> store, const std::string & uri, - const std::string & ref, const std::string & rev, + std::experimental::optional<std::string> ref, const std::string & rev, const std::string & name) { + if (!ref && rev == "" && hasPrefix(uri, "/") && pathExists(uri + "/.git")) { + + bool clean = true; + + try { + runProgram("git", true, { "-C", uri, "diff-index", "--quiet", "HEAD", "--" }); + } catch (ExecError e) { + if (!WIFEXITED(e.status) || WEXITSTATUS(e.status) != 1) throw; + clean = false; + } + + if (!clean) { + + /* This is an unclean working tree. So copy all tracked + files. */ + + GitInfo gitInfo; + gitInfo.rev = "0000000000000000000000000000000000000000"; + gitInfo.shortRev = std::string(gitInfo.rev, 0, 7); + + auto files = tokenizeString<std::set<std::string>>( + runProgram("git", true, { "-C", uri, "ls-files", "-z" }), "\0"s); + + PathFilter filter = [&](const Path & p) -> bool { + assert(hasPrefix(p, uri)); + auto st = lstat(p); + if (S_ISDIR(st.st_mode)) return true; + std::string file(p, uri.size() + 1); + return files.count(file); + }; + + gitInfo.storePath = store->addToStore("source", uri, true, htSHA256, filter); + + return gitInfo; + } + } + + if (!ref) ref = "master"s; + if (rev != "") { std::regex revRegex("^[0-9a-fA-F]{40}$"); if (!std::regex_match(rev, revRegex)) @@ -32,7 +71,7 @@ GitInfo exportGit(ref<Store> store, const std::string & uri, runProgram("git", true, { "init", "--bare", cacheDir }); } - std::string localRef = hashString(htSHA256, fmt("%s-%s", uri, ref)).to_string(Base32, false); + std::string localRef = hashString(htSHA256, fmt("%s-%s", uri, *ref)).to_string(Base32, false); Path localRefFile = cacheDir + "/refs/heads/" + localRef; @@ -47,7 +86,7 @@ GitInfo exportGit(ref<Store> store, const std::string & uri, // FIXME: git stderr messes up our progress indicator, so // we're using --quiet for now. Should process its stderr. - runProgram("git", true, { "-C", cacheDir, "fetch", "--quiet", "--force", "--", uri, ref + ":" + localRef }); + runProgram("git", true, { "-C", cacheDir, "fetch", "--quiet", "--force", "--", uri, *ref + ":" + localRef }); struct timeval times[2]; times[0].tv_sec = now; @@ -67,10 +106,9 @@ GitInfo exportGit(ref<Store> store, const std::string & uri, std::string storeLinkName = hashString(htSHA512, name + std::string("\0"s) + gitInfo.rev).to_string(Base32, false); Path storeLink = cacheDir + "/" + storeLinkName + ".link"; - PathLocks storeLinkLock({storeLink}, fmt("waiting for lock on '%1%'...", storeLink)); + PathLocks storeLinkLock({storeLink}, fmt("waiting for lock on '%1%'...", storeLink)); // FIXME: broken try { - // FIXME: doesn't handle empty lines auto json = nlohmann::json::parse(readFile(storeLink)); assert(json["name"] == name && json["rev"] == gitInfo.rev); @@ -114,7 +152,7 @@ GitInfo exportGit(ref<Store> store, const std::string & uri, static void prim_fetchGit(EvalState & state, const Pos & pos, Value * * args, Value & v) { std::string url; - std::string ref = "master"; + std::experimental::optional<std::string> ref; std::string rev; std::string name = "source"; PathSet context; @@ -145,7 +183,7 @@ static void prim_fetchGit(EvalState & state, const Pos & pos, Value * * args, Va } else url = state.coerceToString(pos, *args[0], context, false, false); - if (hasPrefix(url, "/")) url = "file://" + url; + if (!isUri(url)) url = absPath(url); // FIXME: git externals probably can be used to bypass the URI // whitelist. Ah well. diff --git a/src/libexpr/primops/fetchgit.hh b/src/libexpr/primops/fetchgit.hh index 056b6fcbe..818ab7102 100644 --- a/src/libexpr/primops/fetchgit.hh +++ b/src/libexpr/primops/fetchgit.hh @@ -17,7 +17,8 @@ struct GitInfo }; GitInfo exportGit(ref<Store> store, const std::string & uri, - const std::string & ref, const std::string & rev = "", + std::experimental::optional<std::string> ref = {}, + const std::string & rev = "", const std::string & name = ""); } diff --git a/src/libstore/download.cc b/src/libstore/download.cc index 579a5e8c1..70f9b1f5e 100644 --- a/src/libstore/download.cc +++ b/src/libstore/download.cc @@ -707,7 +707,7 @@ bool isUri(const string & s) size_t pos = s.find("://"); if (pos == string::npos) return false; string scheme(s, 0, pos); - return scheme == "http" || scheme == "https" || scheme == "file" || scheme == "channel" || scheme == "git" || scheme == "s3"; + return scheme == "http" || scheme == "https" || scheme == "file" || scheme == "channel" || scheme == "git" || scheme == "s3" || scheme == "ssh"; } diff --git a/src/libstore/s3-binary-cache-store.cc b/src/libstore/s3-binary-cache-store.cc index 5fc7371a5..6a0f19238 100644 --- a/src/libstore/s3-binary-cache-store.cc +++ b/src/libstore/s3-binary-cache-store.cc @@ -241,8 +241,8 @@ struct S3BinaryCacheStoreImpl : public S3BinaryCacheStore auto & error = res.GetError(); if (error.GetErrorType() == Aws::S3::S3Errors::RESOURCE_NOT_FOUND || error.GetErrorType() == Aws::S3::S3Errors::NO_SUCH_KEY - || (error.GetErrorType() == Aws::S3::S3Errors::UNKNOWN // FIXME - && error.GetMessage().find("404") != std::string::npos)) + // If bucket listing is disabled, 404s turn into 403s + || error.GetErrorType() == Aws::S3::S3Errors::ACCESS_DENIED) return false; throw Error(format("AWS error fetching '%s': %s") % path % error.GetMessage()); } diff --git a/src/libutil/archive.cc b/src/libutil/archive.cc index ea1deb924..f71229d8f 100644 --- a/src/libutil/archive.cc +++ b/src/libutil/archive.cc @@ -29,7 +29,7 @@ const std::string narVersionMagic1 = "nix-archive-1"; static string caseHackSuffix = "~nix~case~hack~"; -PathFilter defaultPathFilter; +PathFilter defaultPathFilter = [](const Path &) { return true; }; static void dumpContents(const Path & path, size_t size, diff --git a/src/libutil/archive.hh b/src/libutil/archive.hh index 607ebf8b2..8a15e849c 100644 --- a/src/libutil/archive.hh +++ b/src/libutil/archive.hh @@ -44,13 +44,6 @@ namespace nix { `+' denotes string concatenation. */ -struct PathFilter -{ - virtual ~PathFilter() { } - virtual bool operator () (const Path & path) { return true; } -}; - -extern PathFilter defaultPathFilter; void dumpPath(const Path & path, Sink & sink, PathFilter & filter = defaultPathFilter); diff --git a/src/libutil/hash.hh b/src/libutil/hash.hh index d83049b02..fd7a61df8 100644 --- a/src/libutil/hash.hh +++ b/src/libutil/hash.hh @@ -93,8 +93,6 @@ Hash hashFile(HashType ht, const Path & path); /* Compute the hash of the given path. The hash is defined as (essentially) hashString(ht, dumpPath(path)). */ -struct PathFilter; -extern PathFilter defaultPathFilter; typedef std::pair<Hash, unsigned long long> HashResult; HashResult hashPath(HashType ht, const Path & path, PathFilter & filter = defaultPathFilter); diff --git a/src/libutil/util.cc b/src/libutil/util.cc index 9346d5dc4..f56153cd4 100644 --- a/src/libutil/util.cc +++ b/src/libutil/util.cc @@ -896,31 +896,45 @@ std::vector<char *> stringsToCharPtrs(const Strings & ss) string runProgram(Path program, bool searchPath, const Strings & args, const std::experimental::optional<std::string> & input) { + RunOptions opts(program, args); + opts.searchPath = searchPath; + opts.input = input; + + auto res = runProgram(opts); + + if (!statusOk(res.first)) + throw ExecError(res.first, fmt("program '%1%' %2%", program, statusToString(res.first))); + + return res.second; +} + +std::pair<int, std::string> runProgram(const RunOptions & options) +{ checkInterrupt(); /* Create a pipe. */ Pipe out, in; out.create(); - if (input) in.create(); + if (options.input) in.create(); /* Fork. */ Pid pid = startProcess([&]() { if (dup2(out.writeSide.get(), STDOUT_FILENO) == -1) throw SysError("dupping stdout"); - if (input && dup2(in.readSide.get(), STDIN_FILENO) == -1) + if (options.input && dup2(in.readSide.get(), STDIN_FILENO) == -1) throw SysError("dupping stdin"); - Strings args_(args); - args_.push_front(program); + Strings args_(options.args); + args_.push_front(options.program); restoreSignals(); - if (searchPath) - execvp(program.c_str(), stringsToCharPtrs(args_).data()); + if (options.searchPath) + execvp(options.program.c_str(), stringsToCharPtrs(args_).data()); else - execv(program.c_str(), stringsToCharPtrs(args_).data()); + execv(options.program.c_str(), stringsToCharPtrs(args_).data()); - throw SysError(format("executing '%1%'") % program); + throw SysError("executing '%1%'", options.program); }); out.writeSide = -1; @@ -935,11 +949,11 @@ string runProgram(Path program, bool searchPath, const Strings & args, }); - if (input) { + if (options.input) { in.readSide = -1; writerThread = std::thread([&]() { try { - writeFull(in.writeSide.get(), *input); + writeFull(in.writeSide.get(), *options.input); promise.set_value(); } catch (...) { promise.set_exception(std::current_exception()); @@ -952,14 +966,11 @@ string runProgram(Path program, bool searchPath, const Strings & args, /* Wait for the child to finish. */ int status = pid.wait(); - if (!statusOk(status)) - throw ExecError(status, format("program '%1%' %2%") - % program % statusToString(status)); /* Wait for the writer thread to finish. */ - if (input) promise.get_future().get(); + if (options.input) promise.get_future().get(); - return result; + return {status, result}; } diff --git a/src/libutil/util.hh b/src/libutil/util.hh index fccf5d854..a3494e09b 100644 --- a/src/libutil/util.hh +++ b/src/libutil/util.hh @@ -245,6 +245,23 @@ string runProgram(Path program, bool searchPath = false, const Strings & args = Strings(), const std::experimental::optional<std::string> & input = {}); +struct RunOptions +{ + Path program; + bool searchPath = true; + Strings args; + std::experimental::optional<std::string> input; + bool _killStderr = false; + + RunOptions(const Path & program, const Strings & args) + : program(program), args(args) { }; + + RunOptions & killStderr(bool v) { _killStderr = true; return *this; } +}; + +std::pair<int, std::string> runProgram(const RunOptions & options); + + class ExecError : public Error { public: @@ -481,4 +498,10 @@ struct MaintainCount std::pair<unsigned short, unsigned short> getWindowSize(); +/* Used in various places. */ +typedef std::function<bool(const Path & path)> PathFilter; + +extern PathFilter defaultPathFilter; + + } |