Skip to content

Commit bfd7cd6

Browse files
committed
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 <[email protected]>
1 parent 03f9ff6 commit bfd7cd6

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed

src/nix/flake-root.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
R""(
2+
3+
# Limitations
4+
- This subcommand doesn't support codebases that keep the flake.nix in a subdirectory.
5+
6+
# Examples
7+
8+
* Get the root folder of a codebase with the shell in folder /path/to/folder and flake.nix in /path/to:
9+
10+
```console
11+
/path/to/folder$ nix flake root
12+
/path/to
13+
14+
/path/to/folder$ nix flake root -r
15+
path:/tmp/eoq
16+
```
17+
18+
* 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
19+
20+
```console
21+
/path/to/folder$ nix flake root
22+
/path/to
23+
24+
/path/to/folder$ nix flake root -r
25+
git+file:///path/to
26+
```
27+
28+
# Description
29+
30+
This command uses the logic used to find flake.nix for commands
31+
such as `nix build` and shows the absolute path, or optionally,
32+
the flake reference.
33+
34+
)""

src/nix/flake.cc

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1343,6 +1343,46 @@ struct CmdFlakePrefetch : FlakeCommand, MixJSON
13431343
}
13441344
};
13451345

1346+
struct CmdFlakeRoot : FlakeCommand
1347+
{
1348+
bool asRef = true;
1349+
CmdFlakeRoot()
1350+
{
1351+
addFlag({
1352+
.longName = "as-ref",
1353+
.shortName = 'r',
1354+
.description = "Show flake root as a normalized flake ref.",
1355+
.handler = {&asRef, false}
1356+
});
1357+
}
1358+
1359+
std::string description() override
1360+
{
1361+
return "get flake root";
1362+
}
1363+
1364+
std::string doc() override
1365+
{
1366+
return
1367+
#include "flake-root.md"
1368+
;
1369+
}
1370+
1371+
void run(nix::ref<nix::Store> store) override
1372+
{
1373+
std::string rootRef = getFlakeRef().to_string();
1374+
if (asRef) {
1375+
int slashIndex = rootRef.find('/');
1376+
while (rootRef[slashIndex + 1] == '/') {
1377+
slashIndex++;
1378+
}
1379+
rootRef = rootRef.substr(slashIndex);
1380+
}
1381+
std::cout << rootRef << std::endl;
1382+
}
1383+
};
1384+
1385+
13461386
struct CmdFlake : NixMultiCommand
13471387
{
13481388
CmdFlake()
@@ -1358,6 +1398,7 @@ struct CmdFlake : NixMultiCommand
13581398
{"archive", []() { return make_ref<CmdFlakeArchive>(); }},
13591399
{"show", []() { return make_ref<CmdFlakeShow>(); }},
13601400
{"prefetch", []() { return make_ref<CmdFlakePrefetch>(); }},
1401+
{"root", []() { return make_ref<CmdFlakeRoot>(); }},
13611402
})
13621403
{
13631404
}

0 commit comments

Comments
 (0)