From 55b691b2e4c709fd52dd1f2297cd722758e12452 Mon Sep 17 00:00:00 2001 From: lucasew Date: Fri, 9 Jun 2023 22:34:42 -0300 Subject: [PATCH] nix: add `nix flake root` Nix already has a logic to go up levels and find the flake.nix. This subcommand just exposes what it finds. Signed-off-by: lucasew --- src/nix/flake-root.md | 34 ++++++++++++++++++++++++++++++++++ src/nix/flake.cc | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 src/nix/flake-root.md diff --git a/src/nix/flake-root.md b/src/nix/flake-root.md new file mode 100644 index 000000000..8bb601345 --- /dev/null +++ b/src/nix/flake-root.md @@ -0,0 +1,34 @@ +R""( + +# Limitations +- This subcommand doesn't support codebases that keep the flake.nix in a subdirectory. + +# Examples + +* Get the root folder of a codebase with the shell in folder /path/to/folder and flake.nix in /path/to: + +```console +/path/to/folder$ nix flake root +/path/to + +/path/to/folder$ nix flake root -r +path:/tmp/eoq +``` + +* Get the root folder of a codebase with the shell in folder /path/to/folder, a flake.nix in /path/to and a git repo initialized + +```console +/path/to/folder$ nix flake root +/path/to + +/path/to/folder$ nix flake root -r +git+file:///path/to +``` + +# Description + +This command uses the logic used to find flake.nix for commands +such as `nix build` and shows the absolute path, or optionally, +the flake reference. + +)"" diff --git a/src/nix/flake.cc b/src/nix/flake.cc index 1eea52e15..9f1d95421 100644 --- a/src/nix/flake.cc +++ b/src/nix/flake.cc @@ -1343,6 +1343,46 @@ struct CmdFlakePrefetch : FlakeCommand, MixJSON } }; +struct CmdFlakeRoot : FlakeCommand +{ + bool asRef = true; + CmdFlakeRoot() + { + addFlag({ + .longName = "as-ref", + .shortName = 'r', + .description = "Show the root as a flakeref in URL-like representation.", + .handler = {&asRef, false} + }); + } + + std::string description() override + { + return "get the root directory of a flake"; + } + + std::string doc() override + { + return + #include "flake-root.md" + ; + } + + void run(nix::ref store) override + { + std::string rootRef = getFlakeRef().to_string(); + if (asRef) { + int slashIndex = rootRef.find('/'); + while (rootRef[slashIndex + 1] == '/') { + slashIndex++; + } + rootRef = rootRef.substr(slashIndex); + } + std::cout << rootRef << std::endl; + } +}; + + struct CmdFlake : NixMultiCommand { CmdFlake() @@ -1358,6 +1398,7 @@ struct CmdFlake : NixMultiCommand {"archive", []() { return make_ref(); }}, {"show", []() { return make_ref(); }}, {"prefetch", []() { return make_ref(); }}, + {"root", []() { return make_ref(); }}, }) { }