thanhnguyen2187 / .phoenix

0 stars 0 forks source link

Learn Nix with `from-zero-to-nix` #2

Closed thanhnguyen2187 closed 1 month ago

thanhnguyen2187 commented 5 months ago

The first lesson is nix run:

echo "Hello Nix" | nix run "nixpkgs#ponysay"

What happened here? The Nix CLI did a few things:

In Nix, every program is part of a package. Packages are built using the Nix language. The ponysay package has a single program (also called ponysay) but packages can contain multiple programs as well as man pages, configuration files, and more. The ffmpeg package, for example, provides both ffmpeg and ffprobe.

thanhnguyen2187 commented 5 months ago

More on terminology:

thanhnguyen2187 commented 5 months ago

The second lesson is nix develop:

nix develop "github:DeterminateSystems/zero-to-nix#example"

It raised:

error: unsupported tarball input attribute 'rev'
(use '--show-trace' to show detailed location information)
thanhnguyen2187 commented 5 months ago

The third lesson is nix build:

A command like this:

nix build "nixpkgs#bat"

Would build bat (a cat alternative in Rust) from scratch, and create a folder named result that contains the built result:

./result/bin/bat --version
# bat 0.24.0

We can also define a local flake.nix file like this:

{
  description = "C++ example flake for Zero to Nix";

  inputs = {
    nixpkgs.url = "https://flakehub.com/f/NixOS/nixpkgs/0.2305.491812.tar.gz";
  };

  outputs = { self, nixpkgs }:
    let
      # Systems supported
      allSystems = [
        "x86_64-linux" # 64-bit Intel/AMD Linux
        "aarch64-linux" # 64-bit ARM Linux
        "x86_64-darwin" # 64-bit Intel macOS
        "aarch64-darwin" # 64-bit ARM macOS
      ];

      # Helper to provide system-specific attributes
      forAllSystems = f: nixpkgs.lib.genAttrs allSystems (system: f {
        pkgs = import nixpkgs { inherit system; };
      });
    in
    {
      packages = forAllSystems ({ pkgs }: {
        default =
          let
            binName = "zero-to-nix-cpp";
            cppDependencies = with pkgs; [ boost gcc poco ];
          in
          pkgs.stdenv.mkDerivation {
            name = "zero-to-nix-cpp";
            src = self;
            buildInputs = cppDependencies;
            buildPhase = "c++ -std=c++17 -o ${binName} ${./main.cpp} -lPocoFoundation -lboost_system";
            installPhase = ''
              mkdir -p $out/bin
              cp ${binName} $out/bin/
            '';
          };
      });
    };
}

And build the local file ourselves:

nix build

The default package is defined and built in this case.