Skip to content

Instantly share code, notes, and snippets.

@thefloweringash
Created January 12, 2020 17:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thefloweringash/d4f58a5b05bc3905bda0636e32c5ea3a to your computer and use it in GitHub Desktop.
Save thefloweringash/d4f58a5b05bc3905bda0636e32c5ea3a to your computer and use it in GitHub Desktop.
nix why-build
#include <iostream>
#include <set>
#include <nix/config.h>
#include <nix/derivations.hh>
#include <nix/store-api.hh>
static nix::ref<nix::Store> openNixStore() {
nix::loadConfFile();
nix::settings.lockCPU = false;
return nix::openStore();
}
class walker {
nix::ref<nix::Store> store;
std::set<std::string> seen;
public:
typedef std::pair<nix::Path, std::string> Input;
walker() : store(openNixStore()) {
}
void whyBuild(const std::string& path, int nesting = 0) {
if (seen.find(path) != seen.end()) {
emit(nesting, path + " [...]");
return;
}
seen.emplace(path);
emit(nesting, path);
const auto &drv = store->derivationFromPath(path);
for (const auto &in : drv.inputDrvs) {
emit(nesting + 1, in.first);
const auto &indrv = store->derivationFromPath(in.first);
for (const auto &inout : in.second) {
const auto &inoutpath = indrv.findOutput(inout);
std::string message = inout;
const bool valid = store->isValidPath(inoutpath);
message += " [" + inoutpath + "] " + (valid ? "valid" : "absent");
emit(nesting + 2, message);
if (! valid) {
whyBuild(in.first, nesting + 3);
}
}
}
}
private:
void emit(int nesting, const std::string& msg) {
std::stringstream prefix;
prefix << "[" << nesting << "] ";
for (int i = 0; i < nesting; i++) {
prefix << " ";
}
std::cout << prefix.str() << msg << std::endl;;
}
};
static void usage() {
std::cout << "Usage: why-build foo.drv" << std::endl;
}
int main(int argc, char **argv) {
if (argc < 2) {
usage();
exit(1);
}
walker w;
w.whyBuild(argv[1]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment