aboutsummaryrefslogtreecommitdiff
path: root/src/libexpr/flake/flakeref.cc
blob: 24af091244596576e2f16311133d88d7656e55b0 (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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
#include "flakeref.hh"
#include "store-api.hh"

#include <regex>

namespace nix {

// A Git ref (i.e. branch or tag name).
const static std::string refRegex = "[a-zA-Z0-9][a-zA-Z0-9_.-]*"; // FIXME: check

// A Git revision (a SHA-1 commit hash).
const static std::string revRegexS = "[0-9a-fA-F]{40}";
std::regex revRegex(revRegexS, std::regex::ECMAScript);

// A Git ref or revision.
const static std::string revOrRefRegex = "(?:(" + revRegexS + ")|(" + refRegex + "))";

// A rev ("e72daba8250068216d79d2aeef40d4d95aff6666"), or a ref
// optionally followed by a rev (e.g. "master" or
// "master/e72daba8250068216d79d2aeef40d4d95aff6666").
const static std::string refAndOrRevRegex = "(?:(" + revRegexS + ")|(?:(" + refRegex + ")(?:/(" + revRegexS + "))?))";

const static std::string flakeAlias = "[a-zA-Z][a-zA-Z0-9_-]*";

// GitHub references.
const static std::string ownerRegex = "[a-zA-Z][a-zA-Z0-9_-]*";
const static std::string repoRegex = "[a-zA-Z][a-zA-Z0-9_-]*";

// URI stuff.
const static std::string schemeRegex = "(?:http|https|ssh|git|file)";
const static std::string authorityRegex = "[a-zA-Z0-9._~-]*";
const static std::string segmentRegex = "[a-zA-Z0-9._~-]+";
const static std::string pathRegex = "/?" + segmentRegex + "(?:/" + segmentRegex + ")*";

// 'dir' path elements cannot start with a '.'. We also reject
// potentially dangerous characters like ';'.
const static std::string subDirElemRegex = "(?:[a-zA-Z0-9_-]+[a-zA-Z0-9._-]*)";
const static std::string subDirRegex = subDirElemRegex + "(?:/" + subDirElemRegex + ")*";


FlakeRef::FlakeRef(const std::string & uri_, bool allowRelative)
{
    // FIXME: could combine this into one regex.

    static std::regex flakeRegex(
        "(?:flake:)?(" + flakeAlias + ")(?:/(?:" + refAndOrRevRegex + "))?",
        std::regex::ECMAScript);

    static std::regex githubRegex(
        "github:(" + ownerRegex + ")/(" + repoRegex + ")(?:/" + revOrRefRegex + ")?",
        std::regex::ECMAScript);

    static std::regex uriRegex(
        "((" + schemeRegex + "):" +
        "(?://(" + authorityRegex + "))?" +
        "(" + pathRegex + "))",
        std::regex::ECMAScript);

    static std::regex refRegex2(refRegex, std::regex::ECMAScript);

    static std::regex subDirRegex2(subDirRegex, std::regex::ECMAScript);

    auto [uri2, params] = splitUriAndParams(uri_);
    std::string uri(uri2);

    auto handleSubdir = [&](const std::string & name, const std::string & value) {
        if (name == "dir") {
            if (value != "" && !std::regex_match(value, subDirRegex2))
                throw BadFlakeRef("flake '%s' has invalid subdirectory '%s'", uri, value);
            subdir = value;
            return true;
        } else
            return false;
    };

    auto handleGitParams = [&](const std::string & name, const std::string & value) {
        if (name == "rev") {
            if (!std::regex_match(value, revRegex))
                throw BadFlakeRef("invalid Git revision '%s'", value);
            rev = Hash(value, htSHA1);
        } else if (name == "ref") {
            if (!std::regex_match(value, refRegex2))
                throw BadFlakeRef("invalid Git ref '%s'", value);
            ref = value;
        } else if (handleSubdir(name, value))
            ;
        else return false;
        return true;
    };

    std::cmatch match;
    if (std::regex_match(uri.c_str(), match, flakeRegex)) {
        IsAlias d;
        d.alias = match[1];
        if (match[2].matched)
            rev = Hash(match[2], htSHA1);
        else if (match[3].matched) {
            ref = match[3];
            if (match[4].matched)
                rev = Hash(match[4], htSHA1);
        }
        data = d;
    }

    else if (std::regex_match(uri.c_str(), match, githubRegex)) {
        IsGitHub d;
        d.owner = match[1];
        d.repo = match[2];
        if (match[3].matched)
            rev = Hash(match[3], htSHA1);
        else if (match[4].matched) {
            ref = match[4];
        }
        for (auto & param : params) {
            if (handleSubdir(param.first, param.second))
                ;
            else
                throw BadFlakeRef("invalid Git flakeref parameter '%s', in '%s'", param.first, uri);
        }
        data = d;
    }

    else if (std::regex_match(uri.c_str(), match, uriRegex)
        && (match[2] == "file" || hasSuffix(match[4], ".git")))
    {
        IsGit d;
        d.uri = match[1];
        for (auto & param : params) {
            if (handleGitParams(param.first, param.second))
                ;
            else
                // FIXME: should probably pass through unknown parameters
                throw BadFlakeRef("invalid Git flakeref parameter '%s', in '%s'", param.first, uri);
        }
        if (rev && !ref)
            throw BadFlakeRef("flake URI '%s' lacks a Git ref", uri);
        data = d;
    }

    else if ((hasPrefix(uri, "/") || (allowRelative && (hasPrefix(uri, "./") || hasPrefix(uri, "../") || uri == ".")))
        && uri.find(':') == std::string::npos)
    {
        IsPath d;
        if (allowRelative) {
            d.path = absPath(uri);
            while (true) {
                if (pathExists(d.path + "/.git")) break;
                subdir = baseNameOf(d.path) + (subdir.empty() ? "" : "/" + subdir);
                d.path = dirOf(d.path);
                if (d.path == "/")
                    throw BadFlakeRef("path '%s' does not reference a Git repository", uri);
            }
        } else
            d.path = canonPath(uri);
        data = d;
        for (auto & param : params) {
            if (handleGitParams(param.first, param.second))
                ;
            else
                throw BadFlakeRef("invalid Git flakeref parameter '%s', in '%s'", param.first, uri);
        }
    }

    else
        throw BadFlakeRef("'%s' is not a valid flake reference", uri);
}

std::string FlakeRef::to_string() const
{
    std::string string;
    bool first = true;

    auto addParam =
        [&](const std::string & name, std::string value) {
            string += first ? '?' : '&';
            first = false;
            string += name;
            string += '=';
            string += value; // FIXME: escaping
        };

    if (auto refData = std::get_if<FlakeRef::IsAlias>(&data)) {
        string = refData->alias;
        if (ref) string += '/' + *ref;
        if (rev) string += '/' + rev->gitRev();
    }

    else if (auto refData = std::get_if<FlakeRef::IsPath>(&data)) {
        string = refData->path;
        if (ref) addParam("ref", *ref);
        if (rev) addParam("rev", rev->gitRev());
        if (subdir != "") addParam("dir", subdir);
    }

    else if (auto refData = std::get_if<FlakeRef::IsGitHub>(&data)) {
        assert(!(ref && rev));
        string = "github:" + refData->owner + "/" + refData->repo;
        if (ref) { string += '/'; string += *ref; }
        if (rev) { string += '/'; string += rev->gitRev(); }
        if (subdir != "") addParam("dir", subdir);
    }

    else if (auto refData = std::get_if<FlakeRef::IsGit>(&data)) {
        assert(!rev || ref);
        string = refData->uri;

        if (ref) {
            addParam("ref", *ref);
            if (rev)
                addParam("rev", rev->gitRev());
        }

        if (subdir != "") addParam("dir", subdir);
    }

    else abort();

    assert(FlakeRef(string) == *this);

    return string;
}

std::ostream & operator << (std::ostream & str, const FlakeRef & flakeRef)
{
    str << flakeRef.to_string();
    return str;
}

bool FlakeRef::isImmutable() const
{
    return (bool) rev;
}

FlakeRef FlakeRef::baseRef() const // Removes the ref and rev from a FlakeRef.
{
    FlakeRef result(*this);
    result.ref = std::nullopt;
    result.rev = std::nullopt;
    return result;
}

std::optional<FlakeRef> parseFlakeRef(
    const std::string & uri, bool allowRelative)
{
    try {
        return FlakeRef(uri, allowRelative);
    } catch (BadFlakeRef & e) {
        return {};
    }
}

}