Skip to content

Commit

Permalink
nix flake prefetch: Add --out-link option
Browse files Browse the repository at this point in the history
This makes `nix flake prefetch` more useful for scripting and prevents
the result from being GC'ed prematurely.
  • Loading branch information
edolstra committed Feb 10, 2025
1 parent 92bf150 commit 254b7af
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/nix/flake-prefetch.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,14 @@ R""(
* Download a tarball and unpack it:

```console
# nix flake prefetch https://cdn.kernel.org/pub/linux/kernel/v5.x/linux-5.10.5.tar.xz
# nix flake prefetch https://cdn.kernel.org/pub/linux/kernel/v5.x/linux-5.10.5.tar.xz --out-link ./result
Downloaded 'https://cdn.kernel.org/pub/linux/kernel/v5.x/linux-5.10.5.tar.xz?narHash=sha256-3XYHZANT6AFBV0BqegkAZHbba6oeDkIUCDwbATLMhAY='
to '/nix/store/sl5vvk8mb4ma1sjyy03kwpvkz50hd22d-source' (hash
'sha256-3XYHZANT6AFBV0BqegkAZHbba6oeDkIUCDwbATLMhAY=').

# cat ./result/README
Linux kernel
```

* Download the `dwarffs` flake (looked up in the flake registry):
Expand Down
18 changes: 18 additions & 0 deletions src/nix/flake.cc
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
#include "markdown.hh"
#include "users.hh"
#include "fetch-to-store.hh"
#include "local-fs-store.hh"

#include <filesystem>
#include <nlohmann/json.hpp>
Expand Down Expand Up @@ -1430,8 +1431,18 @@ struct CmdFlakeShow : FlakeCommand, MixJSON

struct CmdFlakePrefetch : FlakeCommand, MixJSON
{
std::optional<std::filesystem::path> outLink;

CmdFlakePrefetch()
{
addFlag({
.longName = "out-link",
.shortName = 'o',
.description = "Create symlink named *path* to the resulting store path.",
.labels = {"path"},
.handler = {&outLink},
.completer = completePath
});
}

std::string description() override
Expand Down Expand Up @@ -1467,6 +1478,13 @@ struct CmdFlakePrefetch : FlakeCommand, MixJSON
store->printStorePath(storePath),
hash.to_string(HashFormat::SRI, true));
}

if (outLink) {
if (auto store2 = store.dynamic_pointer_cast<LocalFSStore>())
createOutLinks(*outLink, {BuiltPath::Opaque{storePath}}, *store2);
else
throw Error("'--out-link' is not supported for this Nix store");
}
}
};

Expand Down

0 comments on commit 254b7af

Please sign in to comment.