about summary refs log tree commit diff
path: root/src/fix.cc
blob: 052c1d4c91032d116dcb4801278168f996a0eb34 (plain) (blame)
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
#include <iostream>
#include <map>

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>

extern "C" {
#include <aterm2.h>
}

#include "util.hh"


static string nixDescriptorDir;
static string nixSourcesDir;


static bool verbose = false;


/* Mapping of Fix file names to the hashes of the resulting Nix
   descriptors. */
typedef map<string, string> DescriptorMap;


/* Forward declarations. */

void registerFile(string filename)
{
    int res = system(("nix regfile " + filename).c_str());
    if (WEXITSTATUS(res) != 0)
        throw Error("cannot register " + filename + " with Nix");
}


/* Return the directory part of the given path, i.e., everything
   before the final `/'. */
string dirOf(string s)
{
    unsigned int pos = s.rfind('/');
    if (pos == string::npos) throw Error("invalid file name");
    return string(s, 0, pos);
}


/* Return the base name of the given path, i.e., everything following
   the final `/'. */
string baseNameOf(string s)
{
    unsigned int pos = s.rfind('/');
    if (pos == string::npos) throw Error("invalid file name");
    return string(s, pos + 1);
}


/* Download object referenced by the given URL into the sources
   directory.  Return the file name it was downloaded to. */
string fetchURL(string url)
{
    string filename = baseNameOf(url);
    string fullname = nixSourcesDir + "/" + filename;
    struct stat st;
    if (stat(fullname.c_str(), &st)) {
        /* !!! quoting */
        string shellCmd =
            "cd " + nixSourcesDir + " && wget --quiet -N \"" + url + "\"";
        int res = system(shellCmd.c_str());
        if (WEXITSTATUS(res) != 0)
            throw Error("cannot fetch " + url);
    }
    return fullname;
}


Error badTerm(const string & msg, ATerm e)
{
    char * s = ATwriteToString(e);
    return Error(msg + ", in `" + s + "'");
}


/* Term evaluation. */

typedef map<string, ATerm> BindingsMap;

struct EvalContext
{
    string dir;
    DescriptorMap * done;
    BindingsMap * vars;
};


ATerm evaluate(ATerm e, EvalContext ctx);
string instantiateDescriptor(string filename, EvalContext ctx);


string evaluateStr(ATerm e, EvalContext ctx)
{
    e = evaluate(e, ctx);
    char * s;
    if (ATmatch(e, "Str(<str>)", &s))
        return s;
    else throw badTerm("string value expected", e);
}


bool evaluateBool(ATerm e, EvalContext ctx)
{
    e = evaluate(e, ctx);
    if (ATmatch(e, "Bool(True)"))
        return true;
    else if (ATmatch(e, "Bool(False)"))
        return false;
    else throw badTerm("boolean value expected", e);
}


ATerm evaluate(ATerm e, EvalContext ctx)
{
    char * s;
    ATerm e2;
    ATerm eCond, eTrue, eFalse;

    /* Check for normal forms first. */

    if (ATmatch(e, "Str(<str>)", &s) ||
        ATmatch(e, "Bool(True)") || ATmatch(e, "Bool(False)"))
        return e;
    
    else if (
        ATmatch(e, "Pkg(<str>)", &s) || 
        ATmatch(e, "File(<str>)", &s))
    {
        checkHash(s);
        return e;
    }

    /* Short-hands. */

    else if (ATmatch(e, "<str>", &s))
        return ATmake("Str(<str>)", s);

    else if (ATmatch(e, "True", &s))
        return ATmake("Bool(True)", s);

    else if (ATmatch(e, "False", &s))
        return ATmake("Bool(False)", s);

    /* Functions. */

    /* `Var' looks up a variable. */
    else if (ATmatch(e, "Var(<str>)", &s)) {
        string name(s);
        ATerm e2 = (*ctx.vars)[name];
        if (!e2) throw Error("undefined variable " + name);
        return evaluate(e2, ctx); /* !!! update binding */
    }

    /* `Fix' recursively instantiates a Fix descriptor, returning the
       hash of the generated Nix descriptor. */
    else if (ATmatch(e, "Fix(<term>)", &e2)) {
        string filename = absPath(evaluateStr(e2, ctx), ctx.dir); /* !!! */
        return ATmake("Pkg(<str>)",
            instantiateDescriptor(filename, ctx).c_str());
    }

    /* `Source' copies the specified file to nixSourcesDir, registers
       it with Nix, and returns the hash of the file. */
    else if (ATmatch(e, "Source(<term>)", &e2)) {
        string source = absPath(evaluateStr(e2, ctx), ctx.dir); /* !!! */
        string target = nixSourcesDir + "/" + baseNameOf(source);

        // Don't copy if filename is already in nixSourcesDir.
        if (source != target) {
            if (verbose)
                cerr << "copying source " << source << endl;
            string cmd = "cp -p " + source + " " + target;
            int res = system(cmd.c_str());
            if (WEXITSTATUS(res) != 0)
                throw Error("cannot copy " + source + " to " + target);
        }
        
        registerFile(target);
        return ATmake("File(<str>)", hashFile(target).c_str());
    }

    /* `Url' fetches a file from the network, caching it in
       nixSourcesDir and returning the file name. */
    else if (ATmatch(e, "Url(<term>)", &e2)) {
        string url = evaluateStr(e2, ctx);
        if (verbose)
            cerr << "fetching " << url << endl;
        string filename = fetchURL(url);
        return ATmake("Str(<str>)", filename.c_str());
    }

    /* `If' provides conditional evaluation. */
    else if (ATmatch(e, "If(<term>, <term>, <term>)", 
                 &eCond, &eTrue, &eFalse)) 
        return evaluate(evaluateBool(eCond, ctx) ? eTrue : eFalse, ctx);

    else throw badTerm("invalid expression", e);
}


string getStringFromMap(BindingsMap & bindingsMap,
    const string & name)
{
    ATerm e = bindingsMap[name];
    if (!e) throw Error("binding " + name + " is not set");
    char * s;
    if (ATmatch(e, "Str(<str>)", &s))
        return s;
    else
        throw Error("binding " + name + " is not a string");
}


/* Instantiate a Fix descriptors into a Nix descriptor, recursively
   instantiating referenced descriptors as well. */
string instantiateDescriptor(string filename, EvalContext ctx)
{
    /* Already done? */
    DescriptorMap::iterator isInMap = ctx.done->find(filename);
    if (isInMap != ctx.done->end()) return isInMap->second;

    /* No. */
    ctx.dir = dirOf(filename);

    /* Read the Fix descriptor as an ATerm. */
    ATerm inTerm = ATreadFromNamedFile(filename.c_str());
    if (!inTerm) throw Error("cannot read aterm " + filename);

    ATerm bindings;
    if (!ATmatch(inTerm, "Descr(<term>)", &bindings))
        throw Error("invalid term in " + filename);
    
    /* Iterate over the bindings and evaluate them to normal form. */
    BindingsMap bindingsMap; /* the normal forms */
    ctx.vars = &bindingsMap;

    char * cname;
    ATerm value;
    while (ATmatch(bindings, "[Bind(<str>, <term>), <list>]", 
               &cname, &value, &bindings)) 
    {
        string name(cname);
        ATerm e = evaluate(value, ctx);
        bindingsMap[name] = e;
    }

    /* Construct a descriptor identifier by concatenating the package
       and release ids. */
    string pkgId = getStringFromMap(bindingsMap, "pkgId");
    string releaseId = getStringFromMap(bindingsMap, "releaseId");
    string id = pkgId + "-" + releaseId;
    bindingsMap["id"] = ATmake("Str(<str>)", id.c_str());

    /* Add a system name. */
    bindingsMap["system"] = ATmake("Str(<str>)", thisSystem.c_str());
         
    /* Construct the resulting ATerm.  Note that iterating over the
       map yields the bindings in sorted order, which is exactly the
       canonical form for Nix descriptors. */
    ATermList bindingsList = ATempty;
    for (BindingsMap::iterator it = bindingsMap.begin();
         it != bindingsMap.end(); it++)
        /* !!! O(n^2) */
        bindingsList = ATappend(bindingsList,
            ATmake("Bind(<str>, <term>)", it->first.c_str(), it->second));
    ATerm outTerm = ATmake("Descr(<term>)", bindingsList);

    /* Write out the resulting ATerm. */
    string tmpFilename = nixDescriptorDir + "/tmp";
    if (!ATwriteToNamedTextFile(outTerm, tmpFilename.c_str()))
        throw Error("cannot write aterm to " + tmpFilename);

    string outHash = hashFile(tmpFilename);
    string outFilename = nixDescriptorDir + "/" + id + "-" + outHash + ".nix";
    if (rename(tmpFilename.c_str(), outFilename.c_str()))
        throw Error("cannot rename " + tmpFilename + " to " + outFilename);

    /* Register it with Nix. */
    registerFile(outFilename);

    if (verbose)
        cerr << "instantiated " << outHash << " from " << filename << endl;

    (*ctx.done)[filename] = outHash;
    return outHash;
}


/* Instantiate a set of Fix descriptors into Nix descriptors. */
void instantiateDescriptors(Strings filenames)
{
    DescriptorMap done;

    EvalContext ctx;
    ctx.done = &done;

    for (Strings::iterator it = filenames.begin();
         it != filenames.end(); it++)
    {
        string filename = absPath(*it);
        cout << instantiateDescriptor(filename, ctx) << endl;
    }
}


/* Print help. */
void printUsage()
{
    cerr <<
"Usage: fix ...
";
}


/* Parse the command-line arguments, call the right operation. */
void run(Strings::iterator argCur, Strings::iterator argEnd)
{
    Strings extraArgs;
    enum { cmdUnknown, cmdInstantiate } command = cmdUnknown;

    char * homeDir = getenv(nixHomeDirEnvVar.c_str());
    if (homeDir) nixHomeDir = homeDir;

    nixDescriptorDir = nixHomeDir + "/var/nix/descriptors";
    nixSourcesDir = nixHomeDir + "/var/nix/sources";

    for ( ; argCur != argEnd; argCur++) {
        string arg(*argCur);
        if (arg == "-h" || arg == "--help") {
            printUsage();
            return;
        } else if (arg == "-v" || arg == "--verbose") {
            verbose = true;
        } else if (arg == "--instantiate" || arg == "-i") {
            command = cmdInstantiate;
        } else if (arg[0] == '-')
            throw UsageError("invalid option `" + arg + "'");
        else
            extraArgs.push_back(arg);
    }

    switch (command) {

        case cmdInstantiate:
            instantiateDescriptors(extraArgs);
            break;

        default:
            throw UsageError("no operation specified");
    }
}


int main(int argc, char * * argv)
{
    ATerm bottomOfStack;
    ATinit(argc, argv, &bottomOfStack);

    /* Put the arguments in a vector. */
    Strings args;
    while (argc--) args.push_back(*argv++);
    Strings::iterator argCur = args.begin(), argEnd = args.end();

    argCur++;

    try {
        run(argCur, argEnd);
    } catch (UsageError & e) {
        cerr << "error: " << e.what() << endl
             << "Try `fix -h' for more information.\n";
        return 1;
    } catch (exception & e) {
        cerr << "error: " << e.what() << endl;
        return 1;
    }

    return 0;
}