cached-nix-shell 使用教程
项目介绍
cached-nix-shell
是一个用于加速 nix-shell
启动时间的开源项目。它通过缓存机制,使得在后续运行时能够实现即时启动。该项目旨在作为 nix-shell
的一个快速替代品,支持 shebang 脚本和非交互式命令。
项目快速启动
安装
你可以通过以下命令安装 cached-nix-shell
:
# 从 Nixpkgs 安装发布版本
nix-env -iA nixpkgs.cached-nix-shell
# 或者从 GitHub 安装最新开发版本
nix-env -if https://github.com/xzfc/cached-nix-shell/tarball/master
使用
在 shebang 行中替换 nix-shell
为 cached-nix-shell
:
#!/usr/bin/env cached-nix-shell
# nix-shell -i python3 -p python
print("Hello World")
或者直接调用 cached-nix-shell
:
$ cached-nix-shell /hello.py
$ cached-nix-shell -p python3 --run 'python --version'
使用 --wrap
选项包装内部调用 nix-shell
的程序:
$ cached-nix-shell --wrap stack build
应用案例和最佳实践
性能测试
首次运行时,由于没有缓存,启动时间较长:
$ time /hello.py
# 首次运行,无缓存
cached-nix-shell: updating cache
Hello World
/hello.py 0.33s user 0.06s system 91% cpu 0.435 total
后续运行时,由于缓存机制,启动时间显著缩短:
$ time /hello.py
Hello World
/hello.py 0.02s user 0.01s system 97% cpu 0.029 total
缓存和缓存失效
cached-nix-shell
存储由 nix-shell
设置的环境变量,并在后续运行中重用它们。它跟踪 nix
在评估期间读取的文件,并在使用的文件发生变化时执行适当的缓存失效。
典型生态项目
direnv with use_nix
direnv
是一个环境变量管理工具,结合 use_nix
可以实现自动加载 nix-shell
环境。
lorri
lorri
是一个用于项目开发的 nix-shell
替代品,提供更高效的环境管理。
nix-develop
nix-develop
是一个通用的构建工具,具有缓存和即时 shell 命令功能。
home-manager
home-manager
是一个用于管理用户环境的工具,支持 nix-shell
缓存和持久化。
通过这些工具的结合使用,可以进一步提升 nix-shell
的效率和开发体验。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考