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
#include "path-tree.hh"
#include "fs-accessor.hh"
#include "lix/libutil/ansicolor.hh"
#include "lix/libutil/async.hh"
#include "lix/libutil/result.hh"
#include "lix/libutil/strings.hh"
#include "lix/libutil/fmt.hh"
#include <boost/algorithm/string/join.hpp>
#include <queue>

#define ANSI_DIM_ALREADY_VISITED "\e[38;5;244m"

namespace nix {
static std::string hilite(const std::string & s, size_t pos, size_t len,
    const std::string & colour = ANSI_RED)
{
    return
        std::string(s, 0, pos)
        + colour
        + std::string(s, pos, len)
        + ANSI_NORMAL
        + std::string(s, pos + len);
}

static std::string filterPrintable(const std::string & s)
{
    std::string res;
    for (char c : s)
        res += isprint(c) ? c : '.';
    return res;
}

static kj::Promise<Result<std::map<std::string, Strings>>> visitPath(
    const Path & p,
    Store & store,
    const Path & pathS,
    std::string_view dependencyPathHash,
    const std::set<std::string> & hashes,
    const StorePath & from,
    const StorePath & to,
    const ref<FSAccessor> & accessor
)
try {
    /* For each reference, find the files and symlinks that
       contain the reference. */
    std::map<std::string, Strings> hits;
    auto st = TRY_AWAIT(accessor->stat(p));

    auto p2 = p == pathS ? "/" : std::string(p, pathS.size() + 1);

    auto getColour = [&](const std::string & hash) {
        return hash == dependencyPathHash ? ANSI_GREEN : ANSI_BLUE;
    };

    if (st.type == FSAccessor::Type::tDirectory) {
        auto names = TRY_AWAIT(accessor->readDirectory(p));
        for (auto & name : names) {
            auto found = TRY_AWAIT(visitPath(
                p + "/" + name, store, pathS, dependencyPathHash, hashes, from, to, accessor
            ));
            hits.merge(found);
        }
    } else if (st.type == FSAccessor::Type::tRegular) {
        auto contents = TRY_AWAIT(accessor->readFile(p));

        for (auto & hash : hashes) {
            auto pos = contents.find(hash);
            if (pos != std::string::npos) {
                size_t margin = 32;
                auto pos2 = pos >= margin ? pos - margin : 0;
                hits[hash].emplace_back(
                    fmt("%s: …%s…",
                        p2,
                        hilite(
                            filterPrintable(
                                std::string(contents, pos2, pos - pos2 + hash.size() + margin)
                            ),
                            pos - pos2,
                            StorePath::HASH_PART_LEN,
                            getColour(hash)
                        ))
                );
            }
        }
    } else if (st.type == FSAccessor::Type::tSymlink) {
        auto target = TRY_AWAIT(accessor->readLink(p));

        for (auto & hash : hashes) {
            auto pos = target.find(hash);
            if (pos != std::string::npos) {
                hits[hash].emplace_back(fmt(
                    "%s -> %s", p2, hilite(target, pos, StorePath::HASH_PART_LEN, getColour(hash))
                ));
            }
        }
    }

    co_return hits;
} catch (...) {
    co_return result::current_exception();
}

struct Node
{
    StorePath path;
    StorePathSet dependencies;
    StorePathSet dependents;
    std::optional<size_t> dist = std::nullopt;
    Node * prev = nullptr;
    bool queued = false;
    bool visited = false;
};

struct BailOut : BaseException
{};

static kj::Promise<Result<void>> printNode(
    Node & node,
    const std::string & firstPad,
    const std::string & tailPad,
    bool all,
    bool precise,
    Store & store,
    const StorePath & packagePath,
    const StorePath & dependencyPath,
    std::map<StorePath, Node> & graph,
    Strings & output,
    ref<FSAccessor> accessor
)
try {
    auto pathS = store.printStorePath(node.path);

    assert(node.dist.has_value());
    if (precise) {
        output.push_back(
            fmt("%s%s%s%s" ANSI_NORMAL,
                firstPad,
                node.path == dependencyPath ? ANSI_NORMAL
                    : node.visited          ? ANSI_DIM_ALREADY_VISITED
                                            : "",
                firstPad != "" ? "→ " : "",
                pathS)
        );
    }

    if (node.path == dependencyPath && !all && packagePath != dependencyPath) {
        throw BailOut();
    }

    if (node.visited) {
        co_return result::success();
    }

    if (precise) {
        node.visited = true;
    }

    /* Sort the references by distance to `dependency` to
       ensure that the shortest path is printed first. */
    std::multimap<size_t, Node *> refs;
    std::set<std::string> hashes;

    for (auto & ref : node.dependencies) {
        if (ref == node.path && packagePath != dependencyPath) {
            continue;
        }
        auto & node2 = graph.at(ref);
        if (auto dist = node2.dist) {
            refs.emplace(*node2.dist, &node2);
            hashes.insert(std::string(node2.path.hashPart()));
        }
    }

    /* For each reference, find the files and symlinks that
       contain the reference. */
    std::map<std::string, Strings> hits;

    // FIXME: should use scanForReferences().

    if (precise) {
        hits = TRY_AWAIT(visitPath(
            pathS,
            store,
            pathS,
            dependencyPath.hashPart(),
            hashes,
            packagePath,
            dependencyPath,
            accessor
        ));
    }

    for (auto & ref : refs) {
        std::string hash(ref.second->path.hashPart());

        bool last = all ? ref == *refs.rbegin() : true;

        for (auto & hit : hits[hash]) {
            bool first = hit == *hits[hash].begin();
            output.push_back(
                fmt("%s%s%s",
                    tailPad,
                    (first ? (last ? treeLast : treeConn) : (last ? treeNull : treeLine)),
                    hit)
            );
            if (!all) {
                break;
            }
        }

        if (!precise) {
            auto pathS = store.printStorePath(ref.second->path);
            output.push_back(
                fmt("%s%s%s%s" ANSI_NORMAL,
                    firstPad,
                    ref.second->path == dependencyPath ? ANSI_BOLD
                        : ref.second->visited          ? ANSI_DIM_ALREADY_VISITED
                                                       : "",
                    last ? treeLast : treeConn,
                    pathS)
            );
            node.visited = true;
        }

        TRY_AWAIT(printNode(
            *ref.second,
            tailPad + (last ? treeNull : treeLine),
            tailPad + (last ? treeNull : treeLine),
            all,
            precise,
            store,
            packagePath,
            dependencyPath,
            graph,
            output,
            accessor
        ));
    }

    co_return result::success();
} catch (...) {
    co_return result::current_exception();
}

static std::map<StorePath, Node> mkGraph(
    const StorePath & packagePath,
    const StorePath & dependencyPath,
    const std::map<StorePath, StorePathSet> & graph,
    Store & store,
    bool all,
    bool precise
)
{
    std::map<StorePath, Node> graph_data;
    for (auto & [path, dependencies] : graph) {
        graph_data.emplace(
            path,
            Node{
                .path = path,
                .dependencies = dependencies,
                .dist = path == dependencyPath ? std::optional(0) : std::nullopt,
            }
        );
    }

    for (auto & node : graph_data) {
        for (auto & ref : node.second.dependencies) {
            graph_data.at(ref).dependents.insert(node.first);
        }
    }

    /* Run Dijkstra's shortest path algorithm to get the distance
       of every path in the closure to 'dependency'. */
    std::priority_queue<Node *> queue;

    queue.push(&graph_data.at(dependencyPath));
    auto const inf = std::numeric_limits<size_t>::max();

    while (!queue.empty()) {
        auto & node = *queue.top();
        queue.pop();

        for (auto & rref : node.dependents) {
            auto & node2 = graph_data.at(rref);
            auto dist = node.dist.transform([](auto n) { return n + 1; });
            if (dist.value_or(inf) < node2.dist.value_or(inf)) {
                node2.dist = dist;
                node2.prev = &node;
                if (!node2.queued) {
                    node2.queued = true;
                    queue.push(&node2);
                }
            }
        }
    }

    return graph_data;
}

kj::Promise<Result<std::string>> genGraphString(
    const StorePath & start,
    const StorePath & to,
    const std::map<StorePath, StorePathSet> & graphData,
    Store & store,
    bool all,
    bool precise,
    std::optional<ref<FSAccessor>> maybeAccessor
)
try {
    auto graph = mkGraph(start, to, graphData, store, all, precise);
    auto accessor = maybeAccessor ? *maybeAccessor : store.getFSAccessor();

    Strings output;
    if (!precise) {
        output.push_back(fmt("%s", store.printStorePath(graph.at(start).path)));
    }

    try {
        TRY_AWAIT(printNode(
            graph.at(start), "", "", all, precise, store, start, to, graph, output, accessor
        ));
    } catch (BailOut &) {
    }

    co_return concatStringsSep("\n", output);
} catch (...) {
    co_return result::current_exception();
}

}