aboutsummaryrefslogtreecommitdiff
path: root/src/libfetchers/registry.cc
blob: 81b2227de18daa5845f8654ba0869d2bd5f02b96 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
#include "registry.hh"
#include "fetchers.hh"
#include "util.hh"
#include "globals.hh"
#include "store-api.hh"
#include "local-fs-store.hh"

#include <nlohmann/json.hpp>

namespace nix::fetchers {

std::shared_ptr<Registry> Registry::read(
    const Path & path, RegistryType type)
{
    auto registry = std::make_shared<Registry>(type);

    if (!pathExists(path))
        return std::make_shared<Registry>(type);

    try {

        auto json = nlohmann::json::parse(readFile(path));

        auto version = json.value("version", 0);

        if (version == 2) {
            for (auto & i : json["flakes"]) {
                auto toAttrs = jsonToAttrs(i["to"]);
                Attrs extraAttrs;
                auto j = toAttrs.find("dir");
                if (j != toAttrs.end()) {
                    extraAttrs.insert(*j);
                    toAttrs.erase(j);
                }
                auto exact = i.find("exact");
                registry->entries.push_back(
                    Entry {
                        .from = Input::fromAttrs(jsonToAttrs(i["from"])),
                        .to = Input::fromAttrs(std::move(toAttrs)),
                        .extraAttrs = extraAttrs,
                        .exact = exact != i.end() && exact.value()
                    });
            }
        }

        else
            throw Error("flake registry '%s' has unsupported version %d", path, version);

    } catch (nlohmann::json::exception & e) {
        warn("cannot parse flake registry '%s': %s", path, e.what());
    } catch (Error & e) {
        warn("cannot read flake registry '%s': %s", path, e.what());
    }

    return registry;
}

void Registry::write(const Path & path)
{
    nlohmann::json arr;
    for (auto & entry : entries) {
        nlohmann::json obj;
        obj["from"] = attrsToJSON(entry.from.toAttrs());
        obj["to"] = attrsToJSON(entry.to.toAttrs());
        if (!entry.extraAttrs.empty())
            obj["to"].update(attrsToJSON(entry.extraAttrs));
        if (entry.exact)
            obj["exact"] = true;
        arr.emplace_back(std::move(obj));
    }

    nlohmann::json json;
    json["version"] = 2;
    json["flakes"] = std::move(arr);

    createDirs(dirOf(path));
    writeFile(path, json.dump(2));
}

void Registry::add(
    const Input & from,
    const Input & to,
    const Attrs & extraAttrs)
{
    entries.emplace_back(
        Entry {
            .from = from,
            .to = to,
            .extraAttrs = extraAttrs
        });
}

void Registry::remove(const Input & input)
{
    // FIXME: use C++20 std::erase.
    for (auto i = entries.begin(); i != entries.end(); )
        if (i->from == input)
            i = entries.erase(i);
        else
            ++i;
}

static Path getSystemRegistryPath()
{
    return settings.nixConfDir + "/registry.json";
}

static std::shared_ptr<Registry> getSystemRegistry()
{
    static auto systemRegistry =
        Registry::read(getSystemRegistryPath(), Registry::System);
    return systemRegistry;
}

Path getUserRegistryPath()
{
    return getHome() + "/.config/nix/registry.json";
}

std::shared_ptr<Registry> getUserRegistry()
{
    static auto userRegistry =
        Registry::read(getUserRegistryPath(), Registry::User);
    return userRegistry;
}

static std::shared_ptr<Registry> flagRegistry =
    std::make_shared<Registry>(Registry::Flag);

std::shared_ptr<Registry> getFlagRegistry()
{
    return flagRegistry;
}

void overrideRegistry(
    const Input & from,
    const Input & to,
    const Attrs & extraAttrs)
{
    flagRegistry->add(from, to, extraAttrs);
}

static std::shared_ptr<Registry> getGlobalRegistry(ref<Store> store)
{
    static auto reg = [&]() {
        auto path = settings.flakeRegistry.get();

        if (!hasPrefix(path, "/")) {
            auto storePath = downloadFile(store, path, "flake-registry.json", false).storePath;
            if (auto store2 = store.dynamic_pointer_cast<LocalFSStore>())
                store2->addPermRoot(storePath, getCacheDir() + "/nix/flake-registry.json");
            path = store->toRealPath(storePath);
        }

        return Registry::read(path, Registry::Global);
    }();

    return reg;
}

Registries getRegistries(ref<Store> store)
{
    Registries registries;
    registries.push_back(getFlagRegistry());
    registries.push_back(getUserRegistry());
    registries.push_back(getSystemRegistry());
    registries.push_back(getGlobalRegistry(store));
    return registries;
}

std::pair<Input, Attrs> lookupInRegistries(
    ref<Store> store,
    const Input & _input)
{
    Attrs extraAttrs;
    int n = 0;
    Input input(_input);

 restart:

    n++;
    if (n > 100) throw Error("cycle detected in flake registry for '%s'", input.to_string());

    for (auto & registry : getRegistries(store)) {
        // FIXME: O(n)
        for (auto & entry : registry->entries) {
            if (entry.exact) {
                if (entry.from == input) {
                    input = entry.to;
                    extraAttrs = entry.extraAttrs;
                    goto restart;
                }
            } else {
                if (entry.from.contains(input)) {
                    input = entry.to.applyOverrides(
                        !entry.from.getRef() && input.getRef() ? input.getRef() : std::optional<std::string>(),
                        !entry.from.getRev() && input.getRev() ? input.getRev() : std::optional<Hash>());
                    extraAttrs = entry.extraAttrs;
                    goto restart;
                }
            }
        }
    }

    if (!input.isDirect())
        throw Error("cannot find flake '%s' in the flake registries", input.to_string());

    debug("looked up '%s' -> '%s'", _input.to_string(), input.to_string());

    return {input, extraAttrs};
}

}