about summary refs log tree commit diff
path: root/src/libexpr
diff options
context:
space:
mode:
Diffstat (limited to 'src/libexpr')
-rw-r--r--src/libexpr/common-eval-args.hh2
-rw-r--r--src/libexpr/parser.y2
-rw-r--r--src/libexpr/primops.cc46
-rw-r--r--src/libexpr/primops/fetchMercurial.cc198
-rw-r--r--src/libexpr/primops/fetchgit.cc52
-rw-r--r--src/libexpr/primops/fetchgit.hh3
6 files changed, 261 insertions, 42 deletions
diff --git a/src/libexpr/common-eval-args.hh b/src/libexpr/common-eval-args.hh
index 09fa406b2cdc..be7fda783783 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 eee31522830f..7e63dc89f608 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 cd0dfbc03e94..e3b5dfb420b4 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 000000000000..f48d003fcd1d
--- /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 4af5301247bc..4b5ead320c81 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 056b6fcbe78d..818ab7102e97 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 = "");
 
 }