### Example of make-wrapper.sh Usage Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/development/packaging-101.md Demonstrates how to use the `make-wrapper.sh` script for creating wrapper executables in Nix. ```bash #!/bin/sh # This script is used to create wrapper executables. # It is part of Nixpkgs build support. # Example usage (conceptual): # exec "$@" # This would be replaced by actual wrapper logic ``` -------------------------------- ### Nix Configuration for Development Environment Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/faq/index.md Example Nix configuration showing how to install packages, including a custom Python environment with specific packages, for a development setup. This can be used in NixOS or Home Manager configurations. ```nix { # as a nixos module # environment.systemPackages = with pkgs; # # or as a home manager module home.packages = with pkgs; [ lldb (python311.withPackages (ps: with ps; [ ipython pandas requests pyquery pyyaml ] )) ]; } ``` -------------------------------- ### Example of buildFHSEnvBubblewrap Usage Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/development/packaging-101.md Shows how to use `pkgs.buildFHSEnvBubblewrap` to create a Full Host Standard Environment (FHS) using bubblewrap. ```nix # pkgs.buildFHSEnvBubblewrap is used to create FHS environments. # It requires specific arguments and configuration. # Example usage would involve calling this function with appropriate parameters. ``` -------------------------------- ### Instantiate Nixpkgs with a Specific System Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/nixpkgs/multiple-nixpkgs.md A basic example of importing nixpkgs and specifying the target system architecture. The `system` argument is required. ```nix { pkgs-xxx = import nixpkgs { system = "x86_64-linux"; }; } ``` -------------------------------- ### Example of buildFHSEnvChroot Usage Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/development/packaging-101.md Illustrates the use of `pkgs.buildFHSEnvChroot` for creating FHS environments via chroot. ```nix # pkgs.buildFHSEnvChroot is used for creating FHS environments with chroot. # Similar to buildFHSEnvBubblewrap, it requires specific arguments. # Example usage would involve calling this function with appropriate parameters. ``` -------------------------------- ### Example of runCommand Usage Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/development/packaging-101.md Illustrates the basic structure and usage of the `runCommand` function for simple build operations in Nixpkgs. ```nix runCommand "my-package" {} "touch $out/hello && echo hello > $out/world" ``` -------------------------------- ### Testing lib.mkBefore and lib.mkAfter Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/nixos-with-flakes/modularize-the-configuration.md Provides a starting point for testing the usage of lib.mkBefore and lib.mkAfter by setting up a simple Flake project. ```nix # ...... ``` -------------------------------- ### Nix Flakes Module System Configuration Examples Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/other-usage-of-flakes/module-system.md Illustrates three scenarios for configuring options in a NixOS flake, demonstrating correct and incorrect approaches to conditional assignments that can lead to infinite recursion. ```nix { description = "NixOS Flake for Test"; inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-26.05"; outputs = {nixpkgs, ...}: { nixosConfigurations = { "test" = nixpkgs.lib.nixosSystem { modules = [ ({config, lib, ...}: { options = { foo = lib.mkOption { default = false; type = lib.types.bool; }; }; # Scenario 1 (works fine) config.warnings = if config.foo then ["foo"] else []; # Scenario 2 (error: infinite recursion encountered) # config = if config.foo then { warnings = ["foo"];} else {}; # Scenario 3 (works fine) # config = lib.mkIf config.foo {warnings = ["foo"];}; }) ]; }; }; }; } ``` -------------------------------- ### NixOS Home Manager Configuration Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/nixos-with-flakes/start-using-home-manager.md Example configuration for `/etc/nixos/home.nix` to manage user-level settings and packages. Remember to update the username and home directory to your own. ```nix { config, pkgs, ... }: { # TODO please change the username & home directory to your own home.username = "ryan"; home.homeDirectory = "/home/ryan"; # Import files from the current configuration directory into the Nix store, # and create symbolic links pointing to those store files in the Home directory. # home.file.".config/i3/wallpaper.jpg".source = ./wallpaper.jpg; # Import the scripts directory into the Nix store, # and recursively generate symbolic links in the Home directory pointing to the files in the store. # home.file.".config/i3/scripts" = { # source = ./scripts; # recursive = true; # link recursively # executable = true; # make all files executable # }; # encode the file content in nix configuration file directly # home.file.".xxx".text = '' # xxx # ''; # set cursor size and dpi for 4k monitor xresources.properties = { "Xcursor.size" = 16; "Xft.dpi" = 172; }; # Packages that should be installed to the user profile. home.packages = with pkgs; [ # here is some command line tools I use frequently # feel free to add your own or remove some of them neofetch nnn # terminal file manager # archives zip xz unzip p7zip # utils ripgrep # recursively searches directories for a regex pattern jq # A lightweight and flexible command-line JSON processor yq-go # yaml processor https://github.com/mikefarah/yq eza # A modern replacement for ‘ls’ fzf # A command-line fuzzy finder # networking tools mtr # A network diagnostic tool iperf3 dnsutils # `dig` + `nslookup` ldns # replacement of `dig`, it provide the command `drill` aria2 # A lightweight multi-protocol & multi-source command-line download utility socat # replacement of openbsd-netcat nmap # A utility for network discovery and security auditing ipcalc # it is a calculator for the IPv4/v6 addresses # misc cowsay file which tree gnused gnutar gawk zstd gnupg # nix related # # it provides the command `nom` works just like `nix` # with more details log output nix-output-monitor # productivity hugo # static site generator glow # markdown previewer in terminal btop # replacement of htop/nmon iotop # io monitoring iftop # network monitoring # system call monitoring strace # system call monitoring ltrace # library call monitoring lsof # list open files # system tools sysstat lm_sensors # for `sensors` command ethtool pciutils # lspci usbutils # lsusb ]; # basic configuration of git, please change to your own programs.git = { enable = true; userName = "Ryan Yin"; userEmail = "xiaoyin_c@qq.com"; }; # starship - an customizable prompt for any shell programs.starship = { enable = true; # custom settings settings = { add_newline = false; aws.disabled = true; gcloud.disabled = true; line_break.disabled = true; }; }; # alacritty - a cross-platform, GPU-accelerated terminal emulator programs.alacritty = { enable = true; # custom settings settings = { env.TERM = "xterm-256color"; font = { size = 12; draw_bold_text_with_bright_colors = true; }; scrolling.multiplier = 5; selection.save_to_clipboard = true; }; }; programs.bash = { enable = true; enableCompletion = true; # TODO add your custom bashrc here bashrcExtra = '' export PATH="$PATH:$HOME/bin:$HOME/.local/bin:$HOME/go/bin" ''; # set some aliases, feel free to add more or remove some shellAliases = { k = "kubectl"; urldecode = "python3 -c 'import sys, urllib.parse as ul; print(ul.unquote_plus(sys.stdin.read()))'"; urlencode = "python3 -c 'import sys, urllib.parse as ul; print(ul.quote_plus(sys.stdin.read()))'"; }; }; # This value determines the home Manager release that your # configuration is compatible with. This helps avoid breakage # when a new home Manager release introduces backwards # incompatible changes. # # You can update home Manager without changing this value. See # the home Manager release notes for a list of state version # changes in each release. home.stateVersion = "26.05"; } ``` -------------------------------- ### Example Package Definition (pkgs.hello) Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/nixpkgs/overriding.md This snippet shows the structure of a typical package definition in Nixpkgs, highlighting attributes like `pname`, `version`, `src`, and `doCheck` that can be overridden. ```nix { callPackage , lib , stdenv , fetchurl , nixos , testers , hello }: stdenv.mkDerivation (finalAttrs: { pname = "hello"; version = "2.12.1"; src = fetchurl { url = "mirror://gnu/hello/hello-${finalAttrs.version}.tar.gz"; sha256 = "sha256-jZkUKv2SV28wsM18tCqNxoCZmLxdYH2Idh9RLibH2yA="; }; doCheck = true; # ... }) ``` -------------------------------- ### Install MinIO Client on NixOS Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/nix-store/host-your-own-binary-cache-server.md Installs the MinIO command-line client (mc) on your NixOS system. This tool is essential for interacting with MinIO servers, managing buckets, and performing file operations on object storage. ```nix { pkgs, ... }: { environment.systemPackages = with pkgs; [ minio-client # Alternatives for ls, cp, mkdir, diff, and rsync commands for file systems and object storage ]; } ``` -------------------------------- ### Import Overlays Module in NixOS Configuration Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/nixpkgs/overlays.md This example shows how to integrate the overlay module into a NixOS system configuration. It demonstrates importing a local module file that defines the overlays. ```nix # ./flake.nix { inputs = { # ... }; outputs = inputs@{ nixpkgs, ... }: { nixosConfigurations = { my-nixos = nixpkgs.lib.nixosSystem { modules = [ ./configuration.nix # import the module that contains overlays (import ./overlays) ]; }; }; }; } ``` -------------------------------- ### Example Flake Outputs Structure Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/other-usage-of-flakes/outputs.md This example demonstrates the common structure and various types of outputs that can be defined within a `flake.nix` file. It covers checks, packages, apps, formatters, overlays, modules, configurations, dev shells, jobs, and templates. ```nix { inputs = { # ...... }; outputs = { self, ... }@inputs: { # Executed by `nix flake check` checks.""."" = derivation; # Executed by `nix build .#` packages.""."" = derivation; # Executed by `nix build .` packages."".default = derivation; # Executed by `nix run .#` apps.""."" = { type = "app"; program = ""; }; # Executed by `nix run . -- ` apps."".default = { type = "app"; program = "..."; }; # Formatter (alejandra, nixfmt or nixpkgs-fmt) formatter."" = derivation; # Used for nixpkgs packages, also accessible via `nix build .#` legacyPackages.""."" = derivation; # Overlay, consumed by other flakes overlays."" = final: prev: { }; # Default overlay overlays.default = {}; # Nixos module, consumed by other flakes nixosModules."" = { config }: { options = {}; config = {}; }; # Default module nixosModules.default = {}; # Used with `nixos-rebuild --flake .#` # nixosConfigurations."".config.system.build.toplevel must be a derivation nixosConfigurations."" = {}; # Used by `nix develop .#` devShells.""."" = derivation; # Used by `nix develop` devShells."".default = derivation; # Hydra build jobs hydraJobs.""."" = derivation; # Used by `nix flake init -t #` templates."" = { path = ""; description = "template description goes here?"; }; # Used by `nix flake init -t ` templates.default = { path = ""; description = ""; }; }; } ``` -------------------------------- ### Installing `pkgs.runCommand` Wrapper in NixOS System Packages Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/development/intro.md Integrate a `pkgs.runCommand` generated development environment wrapper directly into the NixOS system's environment packages for direct execution. ```nix {pkgs, lib, ...}: environment.systemPackages = [ # Install the wrapper into the system (let packages = with pkgs; [ nodejs_22 pnpm nushell ]; in pkgs.runCommand "dev-shell" { # Dependencies that should exist in the runtime environment buildInputs = packages; # Dependencies that should only exist in the build environment nativeBuildInputs = [ pkgs.makeWrapper ]; } '' mkdir -p $out/bin/ ln -s ${pkgs.nushell}/bin/nu $out/bin/dev-shell wrapProgram $out/bin/dev-shell --prefix PATH : ${pkgs.lib.makeBinPath packages} '') ]; } ``` -------------------------------- ### Basic Nixpkgs Module Structure Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/nixos-with-flakes/nixos-flake-and-module-system.md Illustrates the fundamental structure of a Nixpkgs Module, including how to import other modules and declare options. This is a foundational example for understanding NixOS configuration files. ```nix {lib, config, options, pkgs, ...}: { # Importing other Modules imports = [ # ... ./xxx.nix ]; for.bar.enable = true; # Other option declarations # ... } ``` -------------------------------- ### Development Shell and Build Commands Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/AGENTS.md Commands to enter the development shell, install dependencies, run the development server, build the documentation, fix typos, and format code. ```sh nix develop # enter dev shell (installs pre-commit hooks) pnpm install # install JS deps pnpm run docs:dev # dev server on localhost:5173 pnpm run docs:build # production build (run before committing doc changes) typos -w # auto-fix typos prettier --write . # format all files ``` -------------------------------- ### Basic NixOS Flake Configuration Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/nixos-with-flakes/nixos-with-flakes-enabled.md Example of a basic NixOS flake configuration file. It defines the NixOS package source and specifies the system configuration to be imported. ```nix { description = "A simple NixOS flake"; inputs = { # NixOS official package source, using the nixos-26.05 branch here nixpkgs.url = "github:NixOS/nixpkgs/nixos-26.05"; }; outputs = { self, nixpkgs, ... }@inputs: { # Please replace my-nixos with your hostname nixosConfigurations.my-nixos = nixpkgs.lib.nixosSystem { modules = [ # Import the previous configuration.nix we used, # so the old configuration file still takes effect ./configuration.nix ]; }; }; } ``` -------------------------------- ### Create a new Home Manager flake project Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/nixos-with-flakes/start-using-home-manager.md Use this command to initialize a new NixOS project with Home Manager using a flake template. Ensure you adjust parameters as needed for your setup. ```shell nix flake new example -t github:nix-community/home-manager#nixos ``` -------------------------------- ### Example NixOS kernel configuration Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/nixpkgs/callpackage.md A Nix file defining a custom NixOS kernel configuration, demonstrating how to make the development branch name and kernel source code configurable. ```nix { lib, stdenv, linuxManualConfig, src, boardName, ... }: (linuxManualConfig { version = "5.10.113-thead-1520"; modDirVersion = "5.10.113"; inherit src lib stdenv; # file path to the generated kernel config file(the `.config` generated by make menuconfig) # # here is a special usage to generate a file path from a string configfile = ./. + "${boardName}_config"; allowImportFromDerivation = true; }) ``` -------------------------------- ### Non-Flake Input Example Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/other-usage-of-flakes/inputs.md Shows how to include a dependency that is not a flake, often used for additional source code or configuration files. You can reference files within it using `${inputs.bar}/xxx/xxx.nix`. ```nix { inputs = { bar = { url = "github:foo/bar/branch"; flake = false; }; }; outputs = { self, ... }@inputs: { ... }; } ``` -------------------------------- ### Using sudo to Access Home Manager Packages Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/nixos-with-flakes/start-using-home-manager.md Shows how to use `sudo` to execute commands installed by Home Manager with privileged access. This is the recommended method for running user-installed tools as root. ```shell › sudo kubectl kubectl controls the Kubernetes cluster manager. ... ``` -------------------------------- ### Home Manager vs. NixOS Modules: Package Availability Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/nixos-with-flakes/start-using-home-manager.md Demonstrates that packages installed via Home Manager are available to the user but not to root. This highlights the need for specific access methods when privileged operations are required. ```shell # 1. kubectl is available › kubectl | head kubectl controls the Kubernetes cluster manager. Find more information at: https://kubernetes.io/docs/reference/kubectl/ ...... # 2. switch user to `root` › sudo su # 3. kubectl is no longer available > kubectl Error: nu::shell::external_command × External command failed ╭─[entry #1:1:1] 1 │ kubectl · ───┬─── · ╰── executable was not found ╰──── help: No such file or directory (os error 2) /home/ryan/nix-config> exit ``` -------------------------------- ### Example Nix Module Importing Other Modules Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/nixos-with-flakes/modularize-the-configuration.md This Nix module demonstrates how to import other Nix modules using both direct path import and function call import. It also sets a top-level configuration option. ```nix { config, pkgs, ... }: { imports = [ (import ./special-fonts-1.nix {inherit config pkgs;}) # (1) ./special-fonts-2.nix # (2) ]; fontconfig.enable = true; } ``` -------------------------------- ### Enter a Shell Environment with Specific Packages Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/development/intro.md Use `nix shell` to temporarily enter a shell environment with specified Nix packages like `hello` and `cowsay` installed. This is useful for trying out packages or creating quick, clean environments. ```shell # hello is not available › hello hello: command not found # Enter an environment with the 'hello' and `cowsay` package › nix shell nixpkgs#hello nixpkgs#cowsay # hello is now available › hello Hello, world! # ponysay is also available › cowsay "Hello, world!" _______ < hello > ------- \ ^__^ \ (oo)\л_______ (__)\ )\/л ||----w | || || ``` -------------------------------- ### Install Package from External Flake Input Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/nixos-with-flakes/nixos-flake-and-module-system.md Reference a package from an added flake input within your NixOS configuration. This installs the specified package, for example, the Helix editor from the 'helix' input, into your system's environment. ```nix { config, pkgs, inputs, ... }: { # ... environment.systemPackages = with pkgs; [ git vim wget # Here, the helix package is installed from the helix input data source inputs.helix.packages."${pkgs.stdenv.hostPlatform.system}".helix ]; # ... } ``` -------------------------------- ### Find Why a Package is Installed Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/nixos-with-flakes/other-useful-tips.md Use 'nix-tree' and 'rg' to trace package dependencies and understand why a specific package is installed on your system. ```shell 1. Enter a shell with `nix-tree` & `rg` available: `nix shell nixpkgs#nix-tree nixpkgs#ripgrep` 1. ` nix-store --gc --print-roots | rg -v '/proc/' | rg -Po '(?<= -> ).*' | xargs -o nix-tree` 1. `/` to find the package you want to check. 1. `w` to show the package is depended by which packages, and the full dependency chain. ``` -------------------------------- ### Pip Install Error in NixOS Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/development/dev-environments.md This error occurs when attempting to install Python packages globally in a NixOS environment, as it tries to modify the immutable /nix/store. ```bash › pip install -r requirements.txt error: externally-managed-environment × This environment is externally managed ╰─> This command has been disabled as it tries to modify the immutable `/nix/store` filesystem. To use Python with Nix and nixpkgs, have a look at the online documentation: . note: If you believe this is a mistake, please contact your Python installation or OS distribution provider. You can override this, at the risk of breaking your Python installation or OS, by passing --break-system-packages. hint: See PEP 668 for the detailed specification. ``` -------------------------------- ### Checking Bash Installation Path in NixOS Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/nix-store/intro.md Demonstrates how to check the origin of a command like 'bash' when installed via NixOS, showing its symbolic link within the Nix Store. ```bash # Check where bash in the environment comes from (installed using NixOS) › which bash ╭───┬─────────┬─────────────────────────────────┬──────────╮ │ # │ command │ path │ type │ ├───┼─────────┼─────────────────────────────────┼──────────┤ │ 0 │ bash │ /run/current-system/sw/bin/bash │ external │ ╰───┴─────────┴─────────────────────────────────┴──────────╯ › ls -al /run/current-system/sw/bin/bash lrwxrwxrwx 15 root root 76 1970年 1月 1日 /run/current-system/sw/bin/bash -> /nix/store/1zslabm02hi75anb2w8zjrqwzgs0vrs3-bash-interactive-5.2p26/bin/bash ``` -------------------------------- ### Enter Nixpkgs 'hello' package development environment Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/development/intro.md Use `nix develop` to enter the build environment for the `hello` package from `nixpkgs`. This sets up the environment, including the `CXX` variable and compilation tools. ```shell # login to the build environment of the package `hello` nix develop nixpkgs#hello env | grep CXX CXX=g++ c++ --version g++ (GCC) 12.3.0 Copyright (C) 2022 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. g++ --version g++ (GCC) 12.3.0 Copyright (C) 2022 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ``` -------------------------------- ### Instantiate Nixpkgs for Cross-Compilation Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/nixpkgs/multiple-nixpkgs.md Shows how to set up a nixpkgs instance for cross-compilation, specifying both the local and cross-system configurations, including GCC architecture and ABI flags. Custom overlays can also be applied. ```nix { pkgs-zzz = import nixpkgs { localSystem = "x86_64-linux"; crossSystem = { config = "riscv64-unknown-linux-gnu"; gcc.arch = "rv64gc"; gcc.abi = "lp64d"; }; overlays = [ (self: super: { google-chrome = super.google-chrome.override { commandLineArgs = "--proxy-server='https=127.0.0.1:3128;http=127.0.0.1:3128'"; }; # ... other overlays }); ]; }; } ``` -------------------------------- ### Importing and Configuring a Nix Module Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/other-usage-of-flakes/module-system.md Demonstrates how to import the 'foo.nix' module and configure its options, such as enabling it and setting custom parameters. ```nix # ./bar.nix { config, lib, pkgs, ... }: { imports = [ ./foo.nix ]; programs.foo ={ enable = true; package = pkgs.hello; extraConfig = '' foo baz ''; }; } ``` -------------------------------- ### Show Available Flake Templates Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/nixos-with-flakes/nixos-with-flakes-enabled.md Use this command to list all available templates for initializing a NixOS flake project. ```bash nix flake show templates ``` -------------------------------- ### Instantiate Nixpkgs with Custom Overlays Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/nixpkgs/multiple-nixpkgs.md Demonstrates how to apply custom overlays to a specific nixpkgs instance without affecting the global one. This is useful for modifying packages like google-chrome. ```nix { pkgs-yyy = import nixpkgs { system = "x86_64-linux"; overlays = [ (self: super: { google-chrome = super.google-chrome.override { commandLineArgs = "--proxy-server='https=127.0.0.1:3128;http=127.0.0.1:3128'"; }; # ... other overlays }); ]; }; } ``` -------------------------------- ### Rebuild NixOS System Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/nix-store/host-your-own-binary-cache-server.md Rebuild the NixOS system to apply the new configuration and start using the S3 binary cache. ```bash sudo nixos-rebuild switch --upgrade --flake .# ``` -------------------------------- ### Import and Use a Nix Package from a Separate File Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/nixpkgs/callpackage.md Demonstrates importing a Nix package definition from a separate file (`hello.nix`) within `nix repl`, passing `pkgs` as an argument. ```shell › cat hello.nix pkgs: pkgs.writeShellScriptBin "hello" '' echo "hello, xxx!" '' › nix repl -f '' Welcome to Nix 2.13.5. Type :? for help. warning: Nix search path entry '/nix/var/nix/profiles/per-user/root/channels' does not exist, ignoring Loading installable ''... Added 19203 variables. nix-repl> import ./hello.nix pkgs «derivation /nix/store/zhgar12vfhbajbchj36vbbl3mg6762s8-hello.drv» ``` -------------------------------- ### Check Package Origin with 'which' Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/nix-store/intro.md Use the 'which' command to determine the exact path and origin of an executable, especially when installed via home-manager. ```bash › which cowsay ╭───┬─────────┬────────────────────────────────────────┬──────────╮ │ # │ command │ path │ type │ ├───┼─────────┼────────────────────────────────────────┼──────────┤ │ 0 │ cowsay │ /etc/profiles/per-user/ryan/bin/cowsay │ external │ ╰───┴─────────┴────────────────────────────────────────┴──────────╯ ``` -------------------------------- ### Verify Derivation in Nix REPL Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/nixpkgs/callpackage.md Demonstrates how to load Nixpkgs in `nix repl` and verify that `pkgs.writeShellScriptBin` produces a Derivation. ```shell › nix repl -f '' Welcome to Nix 2.13.5. Type :? for help. Loading installable ''... Added 19203 variables. nix-repl> pkgs.writeShellScriptBin "hello" '' echo "hello, xxx!" '' «derivation /nix/store/zhgar12vfhbajbchj36vbbl3mg6762s8-hello.drv» ``` -------------------------------- ### Initialize Flake with Full Template Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/nixos-with-flakes/nixos-with-flakes-enabled.md Initialize a new NixOS flake project using the 'full' template, which demonstrates all possible usage options. This is followed by viewing the generated flake.nix file. ```bash nix flake init -t templates#full cat flake.nix ``` -------------------------------- ### Show Detailed Error Messages with nixos-rebuild Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/best-practices/debugging.md Use these flags with `nixos-rebuild` to get more detailed error information during deployment. This is useful for diagnosing issues with your NixOS configuration. ```bash cd /etc/nixos sudo nixos-rebuild switch --flake .#myhost --show-trace --print-build-logs --verbose ``` ```bash # A more concise version sudo nixos-rebuild switch --flake .#myhost --show-trace -L -v ``` -------------------------------- ### Creating a Development Environment Wrapper with `pkgs.runCommand` Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/development/intro.md Use `pkgs.runCommand` to create a standalone executable wrapper for a development environment, including specified packages and a custom shell. ```nix { description = "A Nix-flake-based Node.js development environment"; inputs = { nixpkgs.url = "github:nixos/nixpkgs/nixos-26.05"; }; outputs = { self , nixpkgs ,... }: let # system should match the system you are running on system = "x86_64-linux"; in { packages."${system}".dev = let pkgs = import nixpkgs { inherit system; }; packages = with pkgs; [ nodejs_22 pnpm nushell ]; in pkgs.runCommand "dev-shell" { # Dependencies that should exist in the runtime environment buildInputs = packages; # Dependencies that should only exist in the build environment nativeBuildInputs = [ pkgs.makeWrapper ]; } '' mkdir -p $out/bin/ ln -s ${pkgs.nushell}/bin/nu $out/bin/dev-shell wrapProgram $out/bin/dev-shell --prefix PATH : ${pkgs.lib.makeBinPath packages} ''; }; }; } ``` -------------------------------- ### Temporary Git Usage with Nix Run Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/other-usage-of-flakes/the-new-cli.md Use `nix run` to temporarily execute the `git` command for operations like cloning a repository, even if Git is not installed on the system. ```bash nix run nixpkgs#git clone git@github.com:ryan4yin/nix-config.git ``` -------------------------------- ### Using the FHS Environment Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/best-practices/run-downloaded-binaries-on-nixos.md After applying the Nix configuration, use the 'fhs' command to enter the FHS shell. From there, you can execute downloaded binaries. ```shell # Activating FHS drops me into a shell that resembles a "normal" Linux environment. $ fhs # Check what we have in /usr/bin. (fhs) $ ls /usr/bin # Try running a non-NixOS binary downloaded from the Internet. (fhs) $ ./bin/code ``` -------------------------------- ### Using callPackage to import and use a custom kernel configuration Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/nixpkgs/callpackage.md Demonstrates how to use `pkgs.callPackage` within a Nix module to import and utilize a custom kernel configuration, allowing for parameter overrides. ```nix { lib, pkgs, pkgsKernel, kernel-src, ... }: { # ...... boot = { # ...... kernelPackages = pkgs.linuxPackagesFor (pkgs.callPackage ./pkgs/kernel { src = kernel-src; # kernel source is passed as a `specialArgs` and injected into this module. boardName = "licheepi4a"; # the board name, used to generate the kernel config file path. }); # ...... } ``` -------------------------------- ### Input with 'follows' Syntax Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/other-usage-of-flakes/inputs.md Illustrates the 'follows' syntax to ensure a dependency's input (e.g., nixpkgs) aligns with the current flake's inputs, preventing version inconsistencies. ```nix { inputs = { nixpkgs.url = "github:Mic92/nixpkgs/master"; sops-nix = { url = "github:Mic92/sops-nix"; inputs.nixpkgs.follows = "nixpkgs"; }; }; outputs = { self, ... }@inputs: { ... }; } ``` -------------------------------- ### Show Detailed Error Messages with nixos-rebuild Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/nixos-with-flakes/other-useful-tips.md Add flags like --show-trace, --print-build-logs, and --verbose to 'nixos-rebuild' to get detailed error messages during deployment. ```bash cd /etc/nixos sudo nixos-rebuild switch --flake .#myhost --show-trace --print-build-logs --verbose # A more concise version sudo nixos-rebuild switch --flake .#myhost --show-trace -L -v ``` -------------------------------- ### Create and Upload nix-cache-info File Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/nix-store/host-your-own-binary-cache-server.md Creates a 'nix-cache-info' file with essential Nix binary cache metadata and uploads it to the root of the 'nix-cache' S3 bucket. Nix requires this file to identify and use the cache. ```bash cat > nix-cache-info < error: collision between `/nix/store/kvq0gvz6jwggarrcn9a8ramsfhyh1h9d-lldb-14.0.6/lib/python3.11/site-packages/six.py' and `/nix/store/370s8inz4fc9k9lqk4qzj5vyr60q166w-python3-3.11.6-env/lib/python3.11/site-packages/six.py' For full logs, run 'nix log /nix/store/n3scj3s7v9jsb6y3v0fhndw35a9hdbs6-home-manager-path.drv'. ``` -------------------------------- ### Using the 'ponysay' command Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/development/intro.md Demonstrates how to execute the 'ponysay' command from a Nix development environment to display a message. ```bash ./result/bin/ponysay 'hey buddy!' ``` -------------------------------- ### Define a Nix Package in a Separate File Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/nixpkgs/callpackage.md Shows how to define a Nix package in a separate file (`hello.nix`) and pass `pkgs` as a parameter, enhancing maintainability. ```nix pkgs: pkgs.writeShellScriptBin "hello" '' echo "hello, xxx!" '' ``` -------------------------------- ### Temporary Git Usage with Nix Shell Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/other-usage-of-flakes/the-new-cli.md Use `nix shell` to enter an environment with `git` installed, then execute `git` commands. This is an alternative to `nix run` for interactive or multi-command temporary usage. ```bash nix shell nixpkgs#git git clone git@github.com:ryan4yin/nix-config.git ``` -------------------------------- ### Define Nixpkgs Overlays Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/nixpkgs/overlays.md This snippet shows how to define multiple overlays for Nixpkgs. It demonstrates modifying derivations like `google-chrome` and `steam` using `self`/`super` and `final`/`prev` patterns, and how to import overlays from separate files. ```nix # ./overlays/default.nix { config, pkgs, lib, ... }: { nixpkgs.overlays = [ # Overlay 1: Use `self` and `super` to express # the inheritance relationship (self: super: { google-chrome = super.google-chrome.override { commandLineArgs = "--proxy-server='https=127.0.0.1:3128;http=127.0.0.1:3128'"; }; }) # Overlay 2: Use `final` and `prev` to express # the relationship between the new and the old (final: prev: { steam = prev.steam.override { extraPkgs = pkgs: with pkgs; [ keyutils libkrb5 libpng libpulseaudio libvorbis stdenv.cc.cc.lib xorg.libXcursor xorg.libXi xorg.libXinerama xorg.libXScrnSaver ]; extraProfile = "export GDK_SCALE=2"; }; }) # Overlay 3: Define overlays in other files # The content of ./overlays/overlay3/default.nix is the same as above: # `(final: prev: { xxx = prev.xxx.override { ... }; })` (import ./overlay3) ]; } ``` -------------------------------- ### Evaluate Zsh Shell Initialization Source: https://github.com/ryan4yin/nixos-and-flakes-book/blob/main/docs/en/nixos-with-flakes/modularize-the-configuration.md Tests the merging of single-line strings for `programs.zsh.shellInit` using `nix eval`. Demonstrates the concatenated output of before, default, and after directives. ```bash echo $(nix eval .#nixosConfigurations.my-nixos.config.programs.zsh.shellInit) ```