chore: format code via prettier (#125)

This commit is contained in:
Ryan Yin 2024-03-16 18:07:01 +08:00 committed by GitHub
parent af650be728
commit 9e6982f10b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
61 changed files with 311 additions and 395 deletions

2
.github/FUNDING.yml vendored
View File

@ -1,3 +1,3 @@
# open_collective: nixos-and-flakes-book # open_collective: nixos-and-flakes-book
patreon: ryan4yin patreon: ryan4yin
custom: ['https://buymeacoffee.com/ryan4yin', 'https://afdian.net/a/ryan4yin'] custom: ["https://buymeacoffee.com/ryan4yin", "https://afdian.net/a/ryan4yin"]

View File

@ -1,10 +1,9 @@
--- ---
name: Bug report name: Bug report
about: Create a report to help us improve about: Create a report to help us improve
title: '' title: ""
labels: '' labels: ""
assignees: '' assignees: ""
--- ---
**Describe the bug** **Describe the bug**
@ -12,6 +11,7 @@ A clear and concise description of what the bug is.
**To Reproduce** **To Reproduce**
Steps to reproduce the behavior: Steps to reproduce the behavior:
1. Go to '...' 1. Go to '...'
2. Click on '....' 2. Click on '....'
3. Scroll down to '....' 3. Scroll down to '....'
@ -24,8 +24,9 @@ A clear and concise description of what you expected to happen.
If applicable, add screenshots to help explain your problem. If applicable, add screenshots to help explain your problem.
**Environment (please complete the following information):** **Environment (please complete the following information):**
- NixOS Version: [e.g. 23.11]
- Nix version: [e.g. 2.18] - NixOS Version: [e.g. 23.11]
- Nix version: [e.g. 2.18]
**Additional context** **Additional context**
Add any other context about the problem here. Add any other context about the problem here.

View File

@ -1,10 +1,7 @@
--- ---
name: Custom issue template name: Custom issue template
about: Describe this issue template's purpose here. about: Describe this issue template's purpose here.
title: '' title: ""
labels: '' labels: ""
assignees: '' assignees: ""
--- ---

View File

@ -1,10 +1,9 @@
--- ---
name: Feature request name: Feature request
about: Suggest an idea for this project about: Suggest an idea for this project
title: '' title: ""
labels: '' labels: ""
assignees: '' assignees: ""
--- ---
**Is your feature request related to a problem? Please describe.** **Is your feature request related to a problem? Please describe.**

View File

@ -8,43 +8,43 @@ jobs:
generate-pdf: generate-pdf:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Install nix - name: Install nix
uses: cachix/install-nix-action@v23 uses: cachix/install-nix-action@v23
with: with:
nix_path: "nixpkgs=channel:nixpkgs-unstable" nix_path: "nixpkgs=channel:nixpkgs-unstable"
extra_nix_config: | extra_nix_config: |
experimental-features = nix-command flakes experimental-features = nix-command flakes
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }} access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
- name: Show nixpkgs version - name: Show nixpkgs version
run: nix-instantiate --eval -E '(import <nixpkgs> {}).lib.version' run: nix-instantiate --eval -E '(import <nixpkgs> {}).lib.version'
- name: Run a command with nix develop - name: Run a command with nix develop
run: | run: |
nix develop .#export-pdf --ignore-environment --command bash -c ' nix develop .#export-pdf --ignore-environment --command bash -c '
pnpm install pnpm install
pnpm export-pdf pnpm export-pdf
' '
# # For debugging, upload the pdfs as artifacts # # For debugging, upload the pdfs as artifacts
# - uses: actions/upload-artifact@v3 # - uses: actions/upload-artifact@v3
# with: # with:
# name: pdf # name: pdf
# path: '*.pdf' # path: '*.pdf'
- name: Generate changelog - name: Generate changelog
run: | run: |
# Get the previous tag # Get the previous tag
git fetch --tags git fetch --tags
PREVIOUS_TAG=$(git tag --sort=-creatordate | head -n 2 | tail -n 1) PREVIOUS_TAG=$(git tag --sort=-creatordate | head -n 2 | tail -n 1)
# Generate the changelog # Generate the changelog
git log --pretty=format:"%h %s" $PREVIOUS_TAG..HEAD > CHANGELOG git log --pretty=format:"%h %s" $PREVIOUS_TAG..HEAD > CHANGELOG
echo "Changelog from $PREVIOUS_TAG to HEAD:" echo "Changelog from $PREVIOUS_TAG to HEAD:"
cat CHANGELOG cat CHANGELOG
- name: Release PDF - name: Release PDF
uses: softprops/action-gh-release@v1 uses: softprops/action-gh-release@v1
if: startsWith(github.ref, 'refs/tags/') if: startsWith(github.ref, 'refs/tags/')
with: with:
generate_release_notes: true generate_release_notes: true
body_path: CHANGELOG body_path: CHANGELOG
files: | files: |
nixos-and-flakes-book.pdf nixos-and-flakes-book.pdf

View File

@ -1,8 +1,8 @@
import { createRequire } from "module"; import { createRequire } from "module"
import { generateSitemap as sitemap } from "sitemap-ts"; import { generateSitemap as sitemap } from "sitemap-ts"
import { PageData, defineConfig } from "vitepress"; import { PageData, defineConfig } from "vitepress"
const require = createRequire(import.meta.url); const require = createRequire(import.meta.url)
// https://vitepress.dev/reference/site-config // https://vitepress.dev/reference/site-config
export default defineConfig({ export default defineConfig({
@ -18,7 +18,7 @@ export default defineConfig({
hostname: "https://nixos-and-flakes.thiscute.world/", hostname: "https://nixos-and-flakes.thiscute.world/",
outDir: outDir, outDir: outDir,
generateRobotsTxt: true, generateRobotsTxt: true,
}); })
}, },
// SEO Improvement - JSON-LD // SEO Improvement - JSON-LD
@ -30,7 +30,7 @@ export default defineConfig({
["script", { type: "application/ld+json" }, getJSONLD(pageData)], ["script", { type: "application/ld+json" }, getJSONLD(pageData)],
], ],
}, },
}; }
}, },
head: [ head: [
@ -78,14 +78,16 @@ export default defineConfig({
config: (md) => { config: (md) => {
// add support for footnote // add support for footnote
md.use(require("markdown-it-footnote")); md.use(require("markdown-it-footnote"))
}, },
}, },
themeConfig: { themeConfig: {
footer: { footer: {
message: 'Licensed under <a href="http://creativecommons.org/licenses/by-sa/4.0/?ref=chooser-v1" target="_blank">CC BY-SA 4.0</a>', message:
copyright: 'Copyright © 2023-present <a href="https://github.com/ryan4yin" target="_blank">Ryan Yin</a>', 'Licensed under <a href="http://creativecommons.org/licenses/by-sa/4.0/?ref=chooser-v1" target="_blank">CC BY-SA 4.0</a>',
copyright:
'Copyright © 2023-present <a href="https://github.com/ryan4yin" target="_blank">Ryan Yin</a>',
}, },
search: { search: {
@ -115,7 +117,7 @@ export default defineConfig({
root: themeConfigEnglish(), root: themeConfigEnglish(),
zh: themeConfigChinese(), zh: themeConfigChinese(),
}, },
}); })
function themeConfigEnglish() { function themeConfigEnglish() {
return { return {
@ -311,7 +313,7 @@ function themeConfigEnglish() {
}, },
], ],
}, },
}; }
} }
function themeConfigChinese() { function themeConfigChinese() {
@ -401,7 +403,7 @@ function themeConfigChinese() {
items: [ items: [
{ text: "简介", link: "/zh/nixpkgs/intro.md" }, { text: "简介", link: "/zh/nixpkgs/intro.md" },
{ text: "callPackage", link: "/zh/nixpkgs/callpackage.md" }, { text: "callPackage", link: "/zh/nixpkgs/callpackage.md" },
{ text: "Overridding", link: "/zh/nixpkgs/overriding.md" }, { text: "Overriding", link: "/zh/nixpkgs/overriding.md" },
{ text: "Overlays", link: "/zh/nixpkgs/overlays.md" }, { text: "Overlays", link: "/zh/nixpkgs/overlays.md" },
{ {
text: "多 Nixpkgs 实例", text: "多 Nixpkgs 实例",
@ -506,7 +508,7 @@ function themeConfigChinese() {
}, },
], ],
}, },
}; }
} }
function getJSONLD(pageData: PageData) { function getJSONLD(pageData: PageData) {
@ -518,7 +520,7 @@ function getJSONLD(pageData: PageData) {
"inLanguage":"en", "inLanguage":"en",
"description":"An unofficial and opinionated book for beginners", "description":"An unofficial and opinionated book for beginners",
"name":"${pageData.title}" "name":"${pageData.title}"
}`; }`
} else if (pageData.relativePath === "zh/index.md") { } else if (pageData.relativePath === "zh/index.md") {
return `{ return `{
"@context":"http://schema.org", "@context":"http://schema.org",
@ -527,12 +529,12 @@ function getJSONLD(pageData: PageData) {
"inLanguage":"zh-CN", "inLanguage":"zh-CN",
"description":"一份非官方的新手指南", "description":"一份非官方的新手指南",
"name":"${pageData.title}" "name":"${pageData.title}"
}`; }`
} else { } else {
let lang = pageData.relativePath.startsWith("zh/") ? "zh-CN" : "en"; let lang = pageData.relativePath.startsWith("zh/") ? "zh-CN" : "en"
let url = `https:\/\/nixos-and-flakes.thiscute.world\/${pageData.relativePath let url = `https:\/\/nixos-and-flakes.thiscute.world\/${pageData.relativePath
.replace(/\.md$/, "") .replace(/\.md$/, "")
.replace(/\/index\$/, "/")}`; .replace(/\/index\$/, "/")}`
return `{ return `{
"@context":"http://schema.org", "@context":"http://schema.org",
"@type":"TechArticle", "@type":"TechArticle",
@ -544,6 +546,6 @@ function getJSONLD(pageData: PageData) {
}, },
"keywords":"NixOS, Nix, Flakes, Linux, Tutorial", "keywords":"NixOS, Nix, Flakes, Linux, Tutorial",
"url":"${url}" "url":"${url}"
}`; }`
} }
} }

View File

@ -1,7 +1,7 @@
@media print { @media print {
.VPNav, .VPNav,
.VPLocalNav, .VPLocalNav,
.VPDocFooter { .VPDocFooter {
display: none !important; display: none !important;
} }
} }

View File

@ -1,22 +1,22 @@
// .vitepress/theme/index.ts // .vitepress/theme/index.ts
import DefaultTheme from "vitepress/theme"; import DefaultTheme from "vitepress/theme"
import giscusTalk from "vitepress-plugin-comment-with-giscus"; import giscusTalk from "vitepress-plugin-comment-with-giscus"
import { useData, useRoute } from "vitepress"; import { useData, useRoute } from "vitepress"
// custom CSS // custom CSS
import "../style/print.css"; import "../style/print.css"
export default { export default {
// Extending the Default Theme // Extending the Default Theme
...DefaultTheme, ...DefaultTheme,
enhanceApp(ctx) { enhanceApp(ctx) {
DefaultTheme.enhanceApp(ctx); DefaultTheme.enhanceApp(ctx)
// ... // ...
}, },
setup() { setup() {
// Get frontmatter and route // Get frontmatter and route
const { frontmatter } = useData(); const { frontmatter } = useData()
const route = useRoute(); const route = useRoute()
// Obtain configuration from: https://giscus.app/ // Obtain configuration from: https://giscus.app/
giscusTalk( giscusTalk(
@ -41,7 +41,7 @@ export default {
// The default is true, which means enabled, this parameter can be ignored; // The default is true, which means enabled, this parameter can be ignored;
// If it is false, it means it is not enabled. // If it is false, it means it is not enabled.
// You can use `comment: true` preface to enable it separately on the page. // You can use `comment: true` preface to enable it separately on the page.
true, true
); )
}, },
}; }

View File

@ -1,31 +1,30 @@
import { defineUserConfig } from "vitepress-export-pdf"; import { defineUserConfig } from "vitepress-export-pdf"
import config from './config' import config from "./config"
// convert `config.themeConfig?.sidebar` to a list of routes // convert `config.themeConfig?.sidebar` to a list of routes
let routeOrder = []; let routeOrder = []
const sidebar = config.locales.root.themeConfig?.sidebar; const sidebar = config.locales.root.themeConfig?.sidebar
if (sidebar) { if (sidebar) {
sidebar.forEach((it) => { sidebar.forEach((it) => {
if (it.items) { if (it.items) {
it.items.forEach((subItem) => { it.items.forEach((subItem) => {
routeOrder.push(subItem.link.replace(/\.md$/, "")); routeOrder.push(subItem.link.replace(/\.md$/, ""))
}); })
} }
}); })
} }
// print routeOrder in terminal // print routeOrder in terminal
console.log("routeOrder: ", routeOrder); console.log("routeOrder: ", routeOrder)
export default defineUserConfig({ export default defineUserConfig({
routePatterns: ["!/zh/**"], // exclude zh-CN pages routePatterns: ["!/zh/**"], // exclude zh-CN pages
sorter: (pageA, pageB) => { sorter: (pageA, pageB) => {
const aIndex = routeOrder.findIndex(route => route === pageA.path); const aIndex = routeOrder.findIndex((route) => route === pageA.path)
const bIndex = routeOrder.findIndex(route => route === pageB.path); const bIndex = routeOrder.findIndex((route) => route === pageB.path)
const index = aIndex - bIndex; const index = aIndex - bIndex
// console.log(`sorter: ${pageA.path} vs ${pageB.path} = ${index}`); // console.log(`sorter: ${pageA.path} vs ${pageB.path} = ${index}`);
return index; return index
}, },
urlOrigin: "https://nixos-and-flakes.thiscute.world/", urlOrigin: "https://nixos-and-flakes.thiscute.world/",
}); })

View File

@ -5,12 +5,12 @@ Once you have become familiar with NixOS, you can explore advanced topics and di
## Community ## Community
- [Nix Official - Community](https://nixos.org/community/): Contains information about the Nix community, forums, realtime chat, meetups, RFCs, the official team architecture, etc. - [Nix Official - Community](https://nixos.org/community/): Contains information about the Nix community, forums, realtime chat, meetups, RFCs, the official team architecture, etc.
- [Nix Channel Status](https://status.nixos.org/): The build status of each Nix channel. - [Nix Channel Status](https://status.nixos.org/): The build status of each Nix channel.
- [nix-community/NUR](https://github.com/nix-community/NUR): Although Nixpkgs contains a large number of packages, some packages are not included in Nixpkgs due to reasons such as review speed and licensing agreements. NUR is a decentralized Nix package repository where anyone can create their own Nix repository and add it to NUR for others to use. If you want to use a package that is not in Nixpkgs, you can try to find it here. If you want to share your own Nix package with others, you can create and share your own Nix repository according to the README of NUR. - [nix-community/NUR](https://github.com/nix-community/NUR): Although Nixpkgs contains a large number of packages, some packages are not included in Nixpkgs due to reasons such as review speed and licensing agreements. NUR is a decentralized Nix package repository where anyone can create their own Nix repository and add it to NUR for others to use. If you want to use a package that is not in Nixpkgs, you can try to find it here. If you want to share your own Nix package with others, you can create and share your own Nix repository according to the README of NUR.
## Documentation and Videos ## Documentation and Videos
- [Eelco Dolstra - The Purely Functional Software Deployment Model - 2006](https://edolstra.github.io/pubs/phd-thesis.pdf): Eelco Dolstra's seminal PhD thesis about the Nix package manager, - [Eelco Dolstra - The Purely Functional Software Deployment Model - 2006](https://edolstra.github.io/pubs/phd-thesis.pdf): Eelco Dolstra's seminal PhD thesis about the Nix package manager,
- [Nix Reference Manual](https://nixos.org/manual/nix/stable/package-management/profiles.html): A comprehensive guide to the Nix package manager, covering its design and usage from the command line. - [Nix Reference Manual](https://nixos.org/manual/nix/stable/package-management/profiles.html): A comprehensive guide to the Nix package manager, covering its design and usage from the command line.
- [nixpkgs Manual](https://nixos.org/manual/nixpkgs/unstable/): The manual for nixpkgs, which introduces its parameters, explains how to use, modify, and package Nix packages. - [nixpkgs Manual](https://nixos.org/manual/nixpkgs/unstable/): The manual for nixpkgs, which introduces its parameters, explains how to use, modify, and package Nix packages.
- [NixOS Manual](https://nixos.org/manual/nixos/unstable/): A user manual for NixOS, providing configuration instructions for system-level components such as Wayland/X11 and GPU. - [NixOS Manual](https://nixos.org/manual/nixos/unstable/): A user manual for NixOS, providing configuration instructions for system-level components such as Wayland/X11 and GPU.
@ -22,7 +22,6 @@ And there are many official videos on the [NixOS Foundation](https://www.youtube
- [Summer of Nix 2022 — Public Lecture Series](https://www.youtube.com/playlist?list=PLt4-_lkyRrOMWyp5G-m_d1wtTcbBaOxZk): A series of public lectures hosted by the NixOS Foundation, presented by core members of the Nix community such as Eelco Dolstra and Armijn Hemel. The content covers the development history of Nix, the history of NixOS, and the future of Nix, among other topics. - [Summer of Nix 2022 — Public Lecture Series](https://www.youtube.com/playlist?list=PLt4-_lkyRrOMWyp5G-m_d1wtTcbBaOxZk): A series of public lectures hosted by the NixOS Foundation, presented by core members of the Nix community such as Eelco Dolstra and Armijn Hemel. The content covers the development history of Nix, the history of NixOS, and the future of Nix, among other topics.
- [Summer of Nix 2023 — Nix Developer Dialogues](https://www.youtube.com/playlist?list=PLt4-_lkyRrOPcBuz_tjm6ZQb-6rJjU3cf): A series of dialogues between core members of the Nix community in 2023. The content includes the evolution and architectural challenges of Nixpkgs, exploration of Nix's module system, discussion of the Nix ecosystem, AI applications in Nixpkgs, and the application of Nix in the commercial field and open source economics. - [Summer of Nix 2023 — Nix Developer Dialogues](https://www.youtube.com/playlist?list=PLt4-_lkyRrOPcBuz_tjm6ZQb-6rJjU3cf): A series of dialogues between core members of the Nix community in 2023. The content includes the evolution and architectural challenges of Nixpkgs, exploration of Nix's module system, discussion of the Nix ecosystem, AI applications in Nixpkgs, and the application of Nix in the commercial field and open source economics.
## Advanced Techniques and Community Projects ## Advanced Techniques and Community Projects
Once you are comfortable with Flakes, you can explore more advanced techniques and community projects. Here are some popular ones to try out: Once you are comfortable with Flakes, you can explore more advanced techniques and community projects. Here are some popular ones to try out:

View File

@ -158,7 +158,6 @@ outputs.nixosConfigurations.ai.config.home-manager.users.ryan.home.file..config/
As you can see, after loading your Nix flake into the REPL, you can check every attribute of the flake. This capability is very convenient for debugging purposes. As you can see, after loading your Nix flake into the REPL, you can check every attribute of the flake. This capability is very convenient for debugging purposes.
## Debugging functions provided by nixpkgs ## Debugging functions provided by nixpkgs
TODO TODO
@ -172,4 +171,3 @@ TODO
- [How to make nix build display all commands executed by make?](https://www.reddit.com/r/NixOS/comments/14stdgy/how_to_make_nix_build_display_all_commands/) - [How to make nix build display all commands executed by make?](https://www.reddit.com/r/NixOS/comments/14stdgy/how_to_make_nix_build_display_all_commands/)
- use `NIX_DEBUG=7` in derivation - use `NIX_DEBUG=7` in derivation
- [Collection of functions useful for debugging broken nix expressions.](https://github.com/NixOS/nixpkgs/blob/nixos-23.05/lib/debug.nix) - [Collection of functions useful for debugging broken nix expressions.](https://github.com/NixOS/nixpkgs/blob/nixos-23.05/lib/debug.nix)

View File

@ -1,4 +1,4 @@
# Custom NIX_PATH and Flake Registry # Custom NIX_PATH and Flake Registry
## Introduction to NIX_PATH {#nix-path-introduction} ## Introduction to NIX_PATH {#nix-path-introduction}

View File

@ -15,15 +15,15 @@ Let me briefly guide you through using colmena or `nixos-rebuild` for remote dep
Before embarking on remote deployment, a few preparatory steps are necessary: Before embarking on remote deployment, a few preparatory steps are necessary:
1. To prevent remote host's sudo password verification failure, choose one of the following methods: 1. To prevent remote host's sudo password verification failure, choose one of the following methods:
1. Deploy as the remote host's `root` user. 1. Deploy as the remote host's `root` user.
2. Add `security.sudo.wheelNeedsPassword = false;` to the remote host's configuration and manually deploy once in advance to grant the user passwordless sudo permissions.. 2. Add `security.sudo.wheelNeedsPassword = false;` to the remote host's configuration and manually deploy once in advance to grant the user passwordless sudo permissions..
1. **This will allow user-level programs to silently obtain sudo permissions, posing a security risk**! Therefore, if you choose this method, it's advisable to create a dedicated user for remote deployment, rather than using your regular user account! 1. **This will allow user-level programs to silently obtain sudo permissions, posing a security risk**! Therefore, if you choose this method, it's advisable to create a dedicated user for remote deployment, rather than using your regular user account!
2. Configure SSH public key authentication for the remote hosts. 2. Configure SSH public key authentication for the remote hosts.
1. Use the `users.users.<name>.openssh.authorizedKeys.keys` option to complete this task. 1. Use the `users.users.<name>.openssh.authorizedKeys.keys` option to complete this task.
1. Add the remote host's Known Hosts record to your local machine. Otherwise, colmena/nixos-rebuild will fail to deploy due to the inability to verify the remote host's identity. 3. Add the remote host's Known Hosts record to your local machine. Otherwise, colmena/nixos-rebuild will fail to deploy due to the inability to verify the remote host's identity.
1. Use the `programs.ssh.knownHosts` option to add the remote host's public key to the Known Hosts record. 1. Use the `programs.ssh.knownHosts` option to add the remote host's public key to the Known Hosts record.
1. Manually use the `ssh root@<you-host>` command to verify that you can login to the remote host. 4. Manually use the `ssh root@<you-host>` command to verify that you can login to the remote host.
1. If you encounter any issues, resolve them before proceeding. 1. If you encounter any issues, resolve them before proceeding.
It's advisable to use the `root` user for deployment as it's more convenient and avoids the complexities of sudo permissions. It's advisable to use the `root` user for deployment as it's more convenient and avoids the complexities of sudo permissions.
@ -99,7 +99,7 @@ In your system's `flake.nix`, add a new outputs named `colmena`. A simple exampl
Now you can deploy your configuration to the device: Now you can deploy your configuration to the device:
```bash ```bash
nix run nixpkgs#colmena apply nix run nixpkgs#colmena apply
``` ```
For more advanced usage, refer to colmena's official documentation at <https://colmena.cli.rs/unstable/introduction.html> For more advanced usage, refer to colmena's official documentation at <https://colmena.cli.rs/unstable/introduction.html>

View File

@ -77,7 +77,6 @@ idols: aqua ruby kana
idols-debug: aqua-debug ruby-debug kana-debug idols-debug: aqua-debug ruby-debug kana-debug
``` ```
By Save this `Justfile` to the root directory of your Nix flake. Then, I can use `just deploy` to deploy the configuration to my local machine, and `just idols` to deploy the configuration to all my remote servers. By Save this `Justfile` to the root directory of your Nix flake. Then, I can use `just deploy` to deploy the configuration to my local machine, and `just idols` to deploy the configuration to all my remote servers.
This approach simplifies the execution of NixOS commands by abstracting them behind target names in the Justfile, providing a more user-friendly and convenient experience. This approach simplifies the execution of NixOS commands by abstracting them behind target names in the Justfile, providing a more user-friendly and convenient experience.

View File

@ -7,21 +7,20 @@ Luckily, some people in the community have done this for us. The following repos
- [dev-templates](https://github.com/the-nix-way/dev-templates) - [dev-templates](https://github.com/the-nix-way/dev-templates)
- [MordragT/nix-templates](https://github.com/MordragT/nix-templates) - [MordragT/nix-templates](https://github.com/MordragT/nix-templates)
If you think the structure of `flake.nix` is still too complicated and want a simpler way, If you think the structure of `flake.nix` is still too complicated and want a simpler way,
you can consider using the following project, you can consider using the following project,
which encapsulates Nix more thoroughly and provides users with a simpler definition: which encapsulates Nix more thoroughly and provides users with a simpler definition:
- [cachix/devenv](https://github.com/cachix/devenv) - [cachix/devenv](https://github.com/cachix/devenv)
If you don't want to write a single line of nix code and just want to get a reproducible development environment with minimal cost,
If you don't want to write a single line of nix code and just want to get a reproducible development environment with minimal cost,
here's a tool that might meet your needs: here's a tool that might meet your needs:
- [jetpack-io/devbox](https://github.com/jetpack-io/devbox) - [jetpack-io/devbox](https://github.com/jetpack-io/devbox)
## Dev Environment for Python ## Dev Environment for Python
The development environment for Python is much more cumbersome compared to languages like Java or Go because it defaults to installing software in the global environment. The development environment for Python is much more cumbersome compared to languages like Java or Go because it defaults to installing software in the global environment.
To install software for the current project, you must create a virtual environment first (unlike in languages such as JavaScript or Go, To install software for the current project, you must create a virtual environment first (unlike in languages such as JavaScript or Go,
where virtual environments are not necessary). This behavior is very unfriendly for Nix. where virtual environments are not necessary). This behavior is very unfriendly for Nix.
@ -42,10 +41,10 @@ note: If you believe this is a mistake, please contact your Python installation
hint: See PEP 668 for the detailed specification. hint: See PEP 668 for the detailed specification.
``` ```
Based on the error message, `pip install` is directly disabled by NixOS. Even when attempting `pip install --user`, it is similarly disabled. Based on the error message, `pip install` is directly disabled by NixOS. Even when attempting `pip install --user`, it is similarly disabled.
To improve the reproducibility of the environment, Nix eliminates these commands altogether. To improve the reproducibility of the environment, Nix eliminates these commands altogether.
Even if we create a new environment using methods like `mkShell`, Even if we create a new environment using methods like `mkShell`,
these commands still result in errors (presumably because the pip command in Nixpkgs itself has these commands still result in errors (presumably because the pip command in Nixpkgs itself has
been modified to prevent any modification instructions like `install` from running). been modified to prevent any modification instructions like `install` from running).
However, many project installation scripts are based on pip, which means these scripts cannot be used directly. However, many project installation scripts are based on pip, which means these scripts cannot be used directly.
@ -66,8 +65,8 @@ This can be achieved by directly installing the dependencies from `requirements.
There are existing Nix packaging tools available to assist with this: There are existing Nix packaging tools available to assist with this:
> Note that even in these environments, running commands like `pip install` directly will still fail. > Note that even in these environments, running commands like `pip install` directly will still fail.
Python dependencies must be installed through `flake.nix` because the data is located in the `/nix/store` directory, > Python dependencies must be installed through `flake.nix` because the data is located in the `/nix/store` directory,
and these modification commands can only be executed during the Nix build phase. > and these modification commands can only be executed during the Nix build phase.
- [DavHau/mach-nix](https://github.com/DavHau/mach-nix) (currently unmaintained) - [DavHau/mach-nix](https://github.com/DavHau/mach-nix) (currently unmaintained)
- [poetry2nix](https://github.com/nix-community/poetry2nix) - [poetry2nix](https://github.com/nix-community/poetry2nix)
@ -75,8 +74,5 @@ and these modification commands can only be executed during the Nix build phase.
The advantage of these tools is that they utilize the lock mechanism of Nix Flakes to improve reproducibility. The advantage of these tools is that they utilize the lock mechanism of Nix Flakes to improve reproducibility.
However, the downside is that they add an extra layer of abstraction, making the underlying system more complex. However, the downside is that they add an extra layer of abstraction, making the underlying system more complex.
Finally, in some more complex projects, neither of the above solutions may be feasible. Finally, in some more complex projects, neither of the above solutions may be feasible.
In such cases, the best solution is to use containers such as Docker or Podman. Containers have fewer restrictions compared to Nix and can provide the best compatibility. In such cases, the best solution is to use containers such as Docker or Podman. Containers have fewer restrictions compared to Nix and can provide the best compatibility.

View File

@ -139,4 +139,4 @@ Here are some observed issues and limitations:
- [Document available system features - nix#7380](https://github.com/NixOS/nix/issues/7380) - [Document available system features - nix#7380](https://github.com/NixOS/nix/issues/7380)
- [Distributed builds seem to disable local builds - nix#2589](https://github.com/NixOS/nix/issues/2589) - [Distributed builds seem to disable local builds - nix#2589](https://github.com/NixOS/nix/issues/2589)
- [Offloading NixOS builds to a faster machine](https://sgt.hootr.club/molten-matter/nix-distributed-builds/) - [Offloading NixOS builds to a faster machine](https://sgt.hootr.club/molten-matter/nix-distributed-builds/)
- [tests/nixos/remote-builds.nix - Nix Source Code](https://github.com/NixOS/nix/blob/713836112/tests/nixos/remote-builds.nix#L46) - [tests/nixos/remote-builds.nix - Nix Source Code](https://github.com/NixOS/nix/blob/713836112/tests/nixos/remote-builds.nix#L46)

View File

@ -140,14 +140,12 @@ Here is a `flake.nix` that defines a development environment with Node.js 18 ins
Create an empty folder, save the above configuration as `flake.nix`, and then execute `nix develop` (or more precisely, you can use `nix develop .#default`), the current version of nodejs will be outputted, and now you can use `node` `pnpm` `yarn` seamlessly. Create an empty folder, save the above configuration as `flake.nix`, and then execute `nix develop` (or more precisely, you can use `nix develop .#default`), the current version of nodejs will be outputted, and now you can use `node` `pnpm` `yarn` seamlessly.
## Using zsh/fish/... instead of bash ## Using zsh/fish/... instead of bash
`pkgs.mkShell` uses `bash` by default, but you can also use `zsh` or `fish` by add `exec <your-shell>` into `shellHook`. `pkgs.mkShell` uses `bash` by default, but you can also use `zsh` or `fish` by add `exec <your-shell>` into `shellHook`.
Here is an example: Here is an example:
```nix ```nix
{ {
description = "A Nix-flake-based Node.js development environment"; description = "A Nix-flake-based Node.js development environment";
@ -185,7 +183,6 @@ Here is an example:
With the above configuration, `nix develop` will enter the REPL environment of nushell. With the above configuration, `nix develop` will enter the REPL environment of nushell.
## Creating a Development Environment with `pkgs.runCommand` ## Creating a Development Environment with `pkgs.runCommand`
The derivation created by `pkgs.mkShell` cannot be used directly, but must be accessed via `nix develop`. The derivation created by `pkgs.mkShell` cannot be used directly, but must be accessed via `nix develop`.
@ -270,7 +267,6 @@ Related source code:
- [pkgs/build-support/trivial-builders/default.nix - runCommand](https://github.com/NixOS/nixpkgs/blob/nixos-23.11/pkgs/build-support/trivial-builders/default.nix#L21-L49) - [pkgs/build-support/trivial-builders/default.nix - runCommand](https://github.com/NixOS/nixpkgs/blob/nixos-23.11/pkgs/build-support/trivial-builders/default.nix#L21-L49)
- [pkgs/build-support/setup-hooks/make-wrapper.sh](https://github.com/NixOS/nixpkgs/blob/nixos-23.11/pkgs/build-support/setup-hooks/make-wrapper.sh) - [pkgs/build-support/setup-hooks/make-wrapper.sh](https://github.com/NixOS/nixpkgs/blob/nixos-23.11/pkgs/build-support/setup-hooks/make-wrapper.sh)
## Enter the build environment of any Nix package ## Enter the build environment of any Nix package
Now let's take a look at `nix develop`, first read the help document output by `nix develop --help`: Now let's take a look at `nix develop`, first read the help document output by `nix develop --help`:
@ -410,30 +406,30 @@ Here's an example:
nix build "nixpkgs#ponysay" nix build "nixpkgs#ponysay"
# Use the built 'ponysay' command # Use the built 'ponysay' command
./result/bin/ponysay 'hey buddy!' ./result/bin/ponysay 'hey buddy!'
____________ ____________
< hey buddy! > < hey buddy! >
------------ ------------
\ \
\ \
\ \
▄▄ ▄▄ ▄ ▄ ▄▄ ▄▄ ▄ ▄
▀▄▄▄█▄▄▄▄▄█▄▄▄ ▀▄▄▄█▄▄▄▄▄█▄▄▄
▀▄███▄▄██▄██▄▄██ ▀▄███▄▄██▄██▄▄██
▄██▄███▄▄██▄▄▄█▄██ ▄██▄███▄▄██▄▄▄█▄██
█▄█▄██▄█████████▄██ █▄█▄██▄█████████▄██
▄▄█▄█▄▄▄▄▄████████ ▄▄█▄█▄▄▄▄▄████████
▀▀▀▄█▄█▄█▄▄▄▄▄█████ ▄ ▄ ▀▀▀▄█▄█▄█▄▄▄▄▄█████ ▄ ▄
▀▄████▄▄▄█▄█▄▄██ ▄▄▄▄▄█▄▄▄ ▀▄████▄▄▄█▄█▄▄██ ▄▄▄▄▄█▄▄▄
█▄██▄▄▄▄███▄▄▄██ ▄▄▄▄▄▄▄▄▄█▄▄ █▄██▄▄▄▄███▄▄▄██ ▄▄▄▄▄▄▄▄▄█▄▄
▀▄▄██████▄▄▄████ █████████████ ▀▄▄██████▄▄▄████ █████████████
▀▀▀▀▀█████▄▄ ▄▄▄▄▄▄▄▄▄▄██▄█▄▄▀ ▀▀▀▀▀█████▄▄ ▄▄▄▄▄▄▄▄▄▄██▄█▄▄▀
██▄███▄▄▄▄█▄▄▀ ███▄█▄▄▄█▀ ██▄███▄▄▄▄█▄▄▀ ███▄█▄▄▄█▀
█▄██▄▄▄▄▄████ ███████▄██ █▄██▄▄▄▄▄████ ███████▄██
█▄███▄▄█████ ▀███▄█████▄ █▄███▄▄█████ ▀███▄█████▄
██████▀▄▄▄█▄█ █▄██▄▄█▄█▄ ██████▀▄▄▄█▄█ █▄██▄▄█▄█▄
███████ ███████ ▀████▄████ ███████ ███████ ▀████▄████
▀▀█▄▄▄▀ ▀▀█▄▄▄▀ ▀██▄▄██▀█ ▀▀█▄▄▄▀ ▀▀█▄▄▄▀ ▀██▄▄██▀█
▀ ▀▀█ ▀ ▀▀█
``` ```
## Using `nix profile` to manage development environments and entertainment environments ## Using `nix profile` to manage development environments and entertainment environments
@ -458,4 +454,3 @@ There are other commands like `nix flake init`, which you can explore in [New Ni
- [Shell Scripts - NixOS Wiki](https://nixos.wiki/wiki/Shell_Scripts) - [Shell Scripts - NixOS Wiki](https://nixos.wiki/wiki/Shell_Scripts)
[New Nix Commands]: https://nixos.org/manual/nix/stable/command-ref/new-cli/nix.html [New Nix Commands]: https://nixos.org/manual/nix/stable/command-ref/new-cli/nix.html

View File

@ -2,7 +2,6 @@
WIP work in progress, please refer to the following reference documents to learn Nix packaging. WIP work in progress, please refer to the following reference documents to learn Nix packaging.
## 参考文档 ## 参考文档
- [NixOS Series 3: Software Packaging 101](https://lantian.pub/en/article/modify-computer/nixos-packaging.lantian/) - [NixOS Series 3: Software Packaging 101](https://lantian.pub/en/article/modify-computer/nixos-packaging.lantian/)
@ -19,4 +18,3 @@ WIP work in progress, please refer to the following reference documents to learn
- FHS related - FHS related
- [pkgs/build-support/build-fhsenv-bubblewrap/buildFHSEnv.nix](https://github.com/NixOS/nixpkgs/blob/nixos-23.11/pkgs/build-support/build-fhsenv-bubblewrap/buildFHSEnv.nix): `pkgs.buildFHSEnvBubblewrap` - [pkgs/build-support/build-fhsenv-bubblewrap/buildFHSEnv.nix](https://github.com/NixOS/nixpkgs/blob/nixos-23.11/pkgs/build-support/build-fhsenv-bubblewrap/buildFHSEnv.nix): `pkgs.buildFHSEnvBubblewrap`
- [pkgs/build-support/build-fhsenv-chroot/default.nix](https://github.com/NixOS/nixpkgs/blob/nixos-23.11/pkgs/build-support/build-fhsenv-bubblewrap/buildFHSEnv.nix): `pkgs.buildFHSEnvChroot` - [pkgs/build-support/build-fhsenv-chroot/default.nix](https://github.com/NixOS/nixpkgs/blob/nixos-23.11/pkgs/build-support/build-fhsenv-bubblewrap/buildFHSEnv.nix): `pkgs.buildFHSEnvChroot`

View File

@ -19,7 +19,7 @@ When compared to widely used traditional tools like Ansible, Nix has the followi
1. One of the biggest problems with this Ansible is that each deployment is based on incremental changes to the current state of the system. The current state of the system, like the snapshots mentioned above, is not interpretable and is difficult to reproduce. NixOS declares the target state of the system through its configuration files, so that the deployment result is independent of the current state of the system, and repeated deployments will not cause any problems. 1. One of the biggest problems with this Ansible is that each deployment is based on incremental changes to the current state of the system. The current state of the system, like the snapshots mentioned above, is not interpretable and is difficult to reproduce. NixOS declares the target state of the system through its configuration files, so that the deployment result is independent of the current state of the system, and repeated deployments will not cause any problems.
2. Nix Flakes uses a version lock file `flake.lock` to lock the hash value, version number, data source and other information of all dependencies, which greatly improves the reproducibility of the system. Traditional tools like Ansible don't have this feature, so they're not very reproducible. 2. Nix Flakes uses a version lock file `flake.lock` to lock the hash value, version number, data source and other information of all dependencies, which greatly improves the reproducibility of the system. Traditional tools like Ansible don't have this feature, so they're not very reproducible.
1. This is why Docker is so popular - it provides, at a fraction of the cost, a **reproducible system environment on a wide range of machines** that traditional Ops tools like Ansible don't. 1. This is why Docker is so popular - it provides, at a fraction of the cost, a **reproducible system environment on a wide range of machines** that traditional Ops tools like Ansible don't.
1. Nix provides a high degree of ease of system customization by shielding the underlying implementation details with a layer of declarative abstraction so that users only need to care about their core requirements. Tools like Ansible have much weaker abstractions. 3. Nix provides a high degree of ease of system customization by shielding the underlying implementation details with a layer of declarative abstraction so that users only need to care about their core requirements. Tools like Ansible have much weaker abstractions.
1. If you've ever used a declarative configuration tool like terraform/kubernetes, this should be easy to understand. The more complex the requirements, the greater the benefit of declarative configuration. 1. If you've ever used a declarative configuration tool like terraform/kubernetes, this should be easy to understand. The more complex the requirements, the greater the benefit of declarative configuration.
## What are the advantages of Nix compared to Docker container technology? ## What are the advantages of Nix compared to Docker container technology?
@ -71,7 +71,7 @@ this will cause the following error:
```bash ```bash
error: builder for '/nix/store/n3scj3s7v9jsb6y3v0fhndw35a9hdbs6-home-manager-path.drv' failed with exit code 25; error: builder for '/nix/store/n3scj3s7v9jsb6y3v0fhndw35a9hdbs6-home-manager-path.drv' failed with exit code 25;
last 1 log lines: last 1 log lines:
> error: collision between `/nix/store/kvq0gvz6jwggarrcn9a8ramsfhyh1h9d-lldb-14.0.6/lib/python3.11/site-packages/six.py' > 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' 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'. For full logs, run 'nix log /nix/store/n3scj3s7v9jsb6y3v0fhndw35a9hdbs6-home-manager-path.drv'.
``` ```
@ -79,35 +79,34 @@ and `/nix/store/370s8inz4fc9k9lqk4qzj5vyr60q166w-python3-3.11.6-env/lib/python3.
Here are some solutions: Here are some solutions:
1. Split the two packages into two different **profiles**. For example, you can install `lldb` via `environment.systemPackages` and `python311` via `home.packages`. 1. Split the two packages into two different **profiles**. For example, you can install `lldb` via `environment.systemPackages` and `python311` via `home.packages`.
2. Different versions of Python3 are treated as different packages, so you can change your custom Python3 version to `python310` to avoid the conflict. 2. Different versions of Python3 are treated as different packages, so you can change your custom Python3 version to `python310` to avoid the conflict.
2. Use `override` to override the version of the library used by the package to be consistent with the version used by the other package. 3. Use `override` to override the version of the library used by the package to be consistent with the version used by the other package.
```nix ```nix
{ {
# as a nixos module # as a nixos module
# environment.systemPackages = with pkgs; [ # environment.systemPackages = with pkgs; [
# #
# or as a home manager module # or as a home manager module
home.packages = let home.packages = let
custom-python3 = (pkgs.python311.withPackages (ps: custom-python3 = (pkgs.python311.withPackages (ps:
with ps; [ with ps; [
ipython ipython
pandas pandas
requests requests
pyquery pyquery
pyyaml pyyaml
] ]
)); ));
in in
with pkgs; [ with pkgs; [
# override the version of python3 # override the version of python3
# NOTE: This will trigger a rebuild of lldb, it takes time # NOTE: This will trigger a rebuild of lldb, it takes time
(lldb.override { (lldb.override {
python3 = custom-python3; python3 = custom-python3;
}) })
custom-python3
];
}
```
custom-python3
];
}
```

View File

@ -29,6 +29,7 @@ hero:
# - title: Feature C # - title: Feature C
# details: Lorem ipsum dolor sit amet, consectetur adipiscing elit # details: Lorem ipsum dolor sit amet, consectetur adipiscing elit
--- ---
<style> <style>
:root { :root {
--vp-home-hero-name-color: transparent; --vp-home-hero-name-color: transparent;

View File

@ -28,19 +28,18 @@ To my delight, NixOS has exceeded my expectations. The most astonishing aspect i
The rollback capability and reproducibility of NixOS has instilled a great deal of confidence in me—I no longer fear breaking the system. I've even ventured into experimenting with new things on NixOS, such as the hyprland compositor. Previously, on EndeavourOS, I wouldn't have dared to tinker with such novel compositors, as any system mishaps would have entailed significant manual troubleshooting using various workarounds. The rollback capability and reproducibility of NixOS has instilled a great deal of confidence in me—I no longer fear breaking the system. I've even ventured into experimenting with new things on NixOS, such as the hyprland compositor. Previously, on EndeavourOS, I wouldn't have dared to tinker with such novel compositors, as any system mishaps would have entailed significant manual troubleshooting using various workarounds.
As I get more and more involved with NixOS and Nix, I find it also very suitable for synchronously managing the configuration of multiple hosts. As I get more and more involved with NixOS and Nix, I find it also very suitable for synchronously managing the configuration of multiple hosts.
Currently my personal [nix-config](https://github.com/ryan4yin/nix-config) synchronously manages the configuration of many hosts: Currently my personal [nix-config](https://github.com/ryan4yin/nix-config) synchronously manages the configuration of many hosts:
- Desktop computers - Desktop computers
- 1 Macbook Pro 2020 (Intel amd64). - 1 Macbook Pro 2020 (Intel amd64).
- 1 Macbook Pro 2022 (M2 aarch64). - 1 Macbook Pro 2022 (M2 aarch64).
- 1 NixOS desktop PC (amd64). - 1 NixOS desktop PC (amd64).
- Servers - Servers
- 3 NixOS virtual machines (amd64). - 3 NixOS virtual machines (amd64).
- Several development boards for aarch64 and riscv64. - Several development boards for aarch64 and riscv64.
The development environment of three desktop computers is managed by Home Manager, The development environment of three desktop computers is managed by Home Manager,
the main configuration is completely shared, and the configuration modified on any host can be seamlessly synchronized to other hosts through Git. the main configuration is completely shared, and the configuration modified on any host can be seamlessly synchronized to other hosts through Git.
Nix almost completely shielded me from the differences between OS and architecture at the bottom of the three machines, and the experience was very slippery! Nix almost completely shielded me from the differences between OS and architecture at the bottom of the three machines, and the experience was very slippery!

View File

@ -13,7 +13,7 @@ Two reasons:
1. Add cache servers for some third-party projects, such as the nix-community cache server [https://nix-community.cachix.org](https://nix-community.cachix.org), which can significantly improve the build speed of these third-party projects. 1. Add cache servers for some third-party projects, such as the nix-community cache server [https://nix-community.cachix.org](https://nix-community.cachix.org), which can significantly improve the build speed of these third-party projects.
2. Adding a mirrored cache server to accelerate downloads. 2. Adding a mirrored cache server to accelerate downloads.
1. The access speed of the official cache server in China is slow. Without a local global proxy, it is almost unusable. Adding Chinese Nix cache mirrors like ustc/sjtu/tuna can alleviate this issue. 1. The access speed of the official cache server in China is slow. Without a local global proxy, it is almost unusable. Adding Chinese Nix cache mirrors like ustc/sjtu/tuna can alleviate this issue.
## How to Add Custom Cache Servers {#how-to-add-custom-cache-servers} ## How to Add Custom Cache Servers {#how-to-add-custom-cache-servers}
In Nix, you can configure cache servers using the following options: In Nix, you can configure cache servers using the following options:
@ -207,10 +207,10 @@ In other words, you can use it like this:
"https://mirror.sjtu.edu.cn/nix-channels/store" "https://mirror.sjtu.edu.cn/nix-channels/store"
# status: https://mirrors.ustc.edu.cn/status/ # status: https://mirrors.ustc.edu.cn/status/
# "https://mirrors.ustc.edu.cn/nix-channels/store" # "https://mirrors.ustc.edu.cn/nix-channels/store"
"https://cache.nixos.org" "https://cache.nixos.org"
]; ];
trusted-public-keys = [ trusted-public-keys = [
# the default public key of cache.nixos.org, it's built-in, no need to add it here # the default public key of cache.nixos.org, it's built-in, no need to add it here
"cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY=" "cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY="
@ -226,10 +226,10 @@ In other words, you can use it like this:
} }
``` ```
## Accelerate Package Downloads via a Proxy Server {#accelerate-package-downloads-via-a-proxy-server} ## Accelerate Package Downloads via a Proxy Server {#accelerate-package-downloads-via-a-proxy-server}
> Referenced from Issue: [roaming laptop: network proxy configuration - NixOS/nixpkgs](https://github.com/NixOS/nixpkgs/issues/27535#issuecomment-1178444327) > Referenced from Issue: [roaming laptop: network proxy configuration - NixOS/nixpkgs](https://github.com/NixOS/nixpkgs/issues/27535#issuecomment-1178444327)
Although it's mentioned earlier that a transparent proxy running on your router or local machine can completely solve the issue of slow package downloads in NixOS, the configuration is rather cumbersome and often requires additional hardware. > Although it's mentioned earlier that a transparent proxy running on your router or local machine can completely solve the issue of slow package downloads in NixOS, the configuration is rather cumbersome and often requires additional hardware.
More users may prefer to directly speed up package downloads by using a HTTP/Socks5 proxy running on their machine. Here's how to set it up. More users may prefer to directly speed up package downloads by using a HTTP/Socks5 proxy running on their machine. Here's how to set it up.
Using methods like `export HTTPS_PROXY=http://127.0.0.1:7890` in the Terminal will not work because the actual work is done by a background process called `nix-daemon`, not by commands directly executed in the Terminal. Using methods like `export HTTPS_PROXY=http://127.0.0.1:7890` in the Terminal will not work because the actual work is done by a background process called `nix-daemon`, not by commands directly executed in the Terminal.
@ -248,7 +248,7 @@ The implementation code of `nix-daemon` is located at [nixpkgs/nixos/modules/ser
After deploying this configuration, you can check if the environment variables have been set by running `sudo cat /proc/$(pidof nix-daemon)/environ | tr '\0' '\n'`. After deploying this configuration, you can check if the environment variables have been set by running `sudo cat /proc/$(pidof nix-daemon)/environ | tr '\0' '\n'`.
**However, be aware that when the proxy server is not available, nix-daemon will be unable to access any cache servers!** **However, be aware that when the proxy server is not available, nix-daemon will be unable to access any cache servers!**
Therefore, I still recommend using a transparent proxy to address acceleration issues. Therefore, I still recommend using a transparent proxy to address acceleration issues.
If you only need to use a proxy temporarily, you can set the proxy environment variables with the following commands: If you only need to use a proxy temporarily, you can set the proxy environment variables with the following commands:
@ -264,5 +264,5 @@ sudo systemctl restart nix-daemon
``` ```
The settings in `/run/systemd/system/nix-daemon.service.d/override.conf` will be automatically deleted when the system restarts, or you can manually delete it and restart the nix-daemon service to restore the original settings. The settings in `/run/systemd/system/nix-daemon.service.d/override.conf` will be automatically deleted when the system restarts, or you can manually delete it and restart the nix-daemon service to restore the original settings.
> When using some commercial or public proxies, you might encounter HTTP 403 errors when downloading from GitHub (as described in [nixos-and-flakes-book/issues/74](https://github.com/ryan4yin/nixos-and-flakes-book/issues/74)). In such cases, you can try changing the proxy server or setting up [access-tokens](https://github.com/NixOS/nix/issues/6536) to resolve the issue.
> When using some commercial or public proxies, you might encounter HTTP 403 errors when downloading from GitHub (as described in [nixos-and-flakes-book/issues/74](https://github.com/ryan4yin/nixos-and-flakes-book/issues/74)). In such cases, you can try changing the proxy server or setting up [access-tokens](https://github.com/NixOS/nix/issues/6536) to resolve the issue.

View File

@ -277,20 +277,19 @@ echo 'insert after default'
" "
# example 2: single-line string merging # example 2: single-line string merging
echo $(nix eval .#nixosConfigurations.my-nixos.config.programs.zsh.shellInit) echo $(nix eval .#nixosConfigurations.my-nixos.config.programs.zsh.shellInit)
"echo 'insert before default'; "echo 'insert before default';
echo 'this is default'; echo 'this is default';
echo 'insert after default';" echo 'insert after default';"
# Example 3: list merging # Example 3: list merging
nix eval .#nixosConfigurations.my-nixos.config.nix.settings.substituters nix eval .#nixosConfigurations.my-nixos.config.nix.settings.substituters
[ "https://nix-community.cachix.org" "https://nix-community.cachix.org" "https://cache.nixos.org/" "https://ryan4yin.cachix.org" ] [ "https://nix-community.cachix.org" "https://nix-community.cachix.org" "https://cache.nixos.org/" "https://ryan4yin.cachix.org" ]
``` ```
As you can see, `lib.mkBefore` and `lib.mkAfter` can define the order of merging of multiline strings, single-line strings, and lists. The order of merging is the same as the order of definition. As you can see, `lib.mkBefore` and `lib.mkAfter` can define the order of merging of multiline strings, single-line strings, and lists. The order of merging is the same as the order of definition.
> For a deeper introduction to the module system, see [Module System & Custom Options](../other-usage-of-flakes/module-system.md). > For a deeper introduction to the module system, see [Module System & Custom Options](../other-usage-of-flakes/module-system.md).
## References ## References

View File

@ -32,12 +32,11 @@ Compared to the default configuration method currently used in NixOS, Flakes off
} }
``` ```
After making these changes, run `sudo nixos-rebuild switch` to apply the modifications. Then, you can use the Flakes feature to manage your system configuration. After making these changes, run `sudo nixos-rebuild switch` to apply the modifications. Then, you can use the Flakes feature to manage your system configuration.
The new nix command-line tool also offers some convenient features. For example, you can now use the `nix repl` command to open a nix interactive environment. The new nix command-line tool also offers some convenient features. For example, you can now use the `nix repl` command to open a nix interactive environment.
If you're interested, you can use it to review and test all the Nix syntax you've learned before. If you're interested, you can use it to review and test all the Nix syntax you've learned before.
## Switching System Configuration to `flake.nix` {#switch-to-flake-nix} ## Switching System Configuration to `flake.nix` {#switch-to-flake-nix}
After enabling the Flakes feature, the `sudo nixos-rebuild switch` command will prioritize reading the `/etc/nixos/flake.nix` file, and if it's not found, it will attempt to use `/etc/nixos/configuration.nix`. After enabling the Flakes feature, the `sudo nixos-rebuild switch` command will prioritize reading the `/etc/nixos/flake.nix` file, and if it's not found, it will attempt to use `/etc/nixos/configuration.nix`.
@ -56,7 +55,7 @@ nix flake init -t templates#full
cat flake.nix cat flake.nix
``` ```
Referencing this template, create the file `/etc/nixos/flake.nix` and write the configuration content. All subsequent system modifications will be taken over by Nix Flakes. Referencing this template, create the file `/etc/nixos/flake.nix` and write the configuration content. All subsequent system modifications will be taken over by Nix Flakes.
Here's an example of the content: Here's an example of the content:
```nix{16} ```nix{16}
@ -86,7 +85,7 @@ Here we defined a system named `my-nixos`, with its configuration file located a
Now, when you execute `sudo nixos-rebuild switch` to apply the configuration, the system should not change at all because we have simply switched to using Nix Flakes, and the configuration content remains consistent with before. Now, when you execute `sudo nixos-rebuild switch` to apply the configuration, the system should not change at all because we have simply switched to using Nix Flakes, and the configuration content remains consistent with before.
After the switch, we can manage the system through the Flakes feature. After the switch, we can manage the system through the Flakes feature.
Currently, our flake includes these files: Currently, our flake includes these files:
@ -97,11 +96,10 @@ Currently, our flake includes these files:
Up to this point, `/etc/nixos/flake.nix` has merely been a thin wrapper around `/etc/nixos/configuration.nix`, offering no new functionality and introducing no disruptive changes. In the content of the book that follows, we will gradually see the benefits that such a wrapper brings. Up to this point, `/etc/nixos/flake.nix` has merely been a thin wrapper around `/etc/nixos/configuration.nix`, offering no new functionality and introducing no disruptive changes. In the content of the book that follows, we will gradually see the benefits that such a wrapper brings.
> Note: The configuration management method described in this book is NOT "Everything in a single file". It is recommended to categorize configuration content into different nix files, then introduce these configuration files in the `modules` list of `flake.nix`, and manage them with Git. > Note: The configuration management method described in this book is NOT "Everything in a single file". It is recommended to categorize configuration content into different nix files, then introduce these configuration files in the `modules` list of `flake.nix`, and manage them with Git.
> >
> The benefits of this approach are better organization of configuration files and improved maintainability of the configuration. The section [Modularizing NixOS Configuration](./modularize-the-configuration.md) will explain in detail how to modularize your NixOS configuration, and [Other Useful Tips - Managing NixOS Configuration with Git](./other-useful-tips.md) will introduce several best practices for managing NixOS configuration with Git. > The benefits of this approach are better organization of configuration files and improved maintainability of the configuration. The section [Modularizing NixOS Configuration](./modularize-the-configuration.md) will explain in detail how to modularize your NixOS configuration, and [Other Useful Tips - Managing NixOS Configuration with Git](./other-useful-tips.md) will introduce several best practices for managing NixOS configuration with Git.
## `flake.nix` Configuration Explained {#flake-nix-configuration-explained} ## `flake.nix` Configuration Explained {#flake-nix-configuration-explained}
Above, we created a `flake.nix` file to manage system configurations, but you might still be unclear about its structure. Let's explain the content of this file in detail. Above, we created a `flake.nix` file to manage system configurations, but you might still be unclear about its structure. Let's explain the content of this file in detail.
@ -123,18 +121,17 @@ First, let's look at the `inputs` attribute. It is an attribute set that defines
} }
``` ```
Dependencies in `inputs` has many types and definitions. Dependencies in `inputs` has many types and definitions.
It can be another flake, a regular Git repository, or a local path. It can be another flake, a regular Git repository, or a local path.
The section [Other Usage of Flakes - Flake Inputs](../other-usage-of-flakes/inputs.md) describes common types of dependencies and their definitions in detail. The section [Other Usage of Flakes - Flake Inputs](../other-usage-of-flakes/inputs.md) describes common types of dependencies and their definitions in detail.
Here we only define a dependency named `nixpkgs`, which is the most common way to reference in a flake, i.e., `github:owner/name/reference`. The `reference` here can be a branch name, commit-id, or tag. Here we only define a dependency named `nixpkgs`, which is the most common way to reference in a flake, i.e., `github:owner/name/reference`. The `reference` here can be a branch name, commit-id, or tag.
After `nixpkgs` is defined in `inputs`, you can use it in the parameters of the subsequent `outputs` function, which is exactly what our example does. After `nixpkgs` is defined in `inputs`, you can use it in the parameters of the subsequent `outputs` function, which is exactly what our example does.
### 2. Flake Outputs ### 2. Flake Outputs
Now let's look at `outputs`. Now let's look at `outputs`.
It is a function that takes the dependencies from `inputs` as its parameters, and its return value is an attribute set, which represents the build results of the flake: It is a function that takes the dependencies from `inputs` as its parameters, and its return value is an attribute set, which represents the build results of the flake:
```nix{11-19} ```nix{11-19}
@ -160,12 +157,12 @@ It is a function that takes the dependencies from `inputs` as its parameters, an
} }
``` ```
Flakes can have various purposes and can have different types of outputs. The section [Flake Outputs](../other-usage-of-flakes/outputs.md) provides a more detailed introduction. Flakes can have various purposes and can have different types of outputs. The section [Flake Outputs](../other-usage-of-flakes/outputs.md) provides a more detailed introduction.
Here, we are only using the `nixosConfigurations` type of outputs, which is used to configure NixOS systems. Here, we are only using the `nixosConfigurations` type of outputs, which is used to configure NixOS systems.
When we run the `sudo nixos-rebuild switch` command, it looks for the `nixosConfigurations.my-nixos` attribute (where `my-nixos` will be the hostname of your current system) in the attribute set returned by the `outputs` function of `/etc/nixos/flake.nix` and uses the definition there to configure your NixOS system. When we run the `sudo nixos-rebuild switch` command, it looks for the `nixosConfigurations.my-nixos` attribute (where `my-nixos` will be the hostname of your current system) in the attribute set returned by the `outputs` function of `/etc/nixos/flake.nix` and uses the definition there to configure your NixOS system.
Actually, we can also customize the location of the flake and the name of the NixOS configuration instead of using the defaults. Actually, we can also customize the location of the flake and the name of the NixOS configuration instead of using the defaults.
This can be done by adding the `--flake` parameter to the `nixos-rebuild` command. Here's an example: This can be done by adding the `--flake` parameter to the `nixos-rebuild` command. Here's an example:
```nix ```nix
@ -218,7 +215,7 @@ The attribute set following `nixpkgs.lib.nixosSystem` is the function's paramete
1. `system`: This is straightforward, it's the system architecture parameter. 1. `system`: This is straightforward, it's the system architecture parameter.
2. `modules`: This is a list of modules, where the actual NixOS system configuration is defined. 2. `modules`: This is a list of modules, where the actual NixOS system configuration is defined.
The `/etc/nixos/configuration.nix` configuration file itself is a Nixpkgs Module, so it can be directly added to the `modules` list for use. The `/etc/nixos/configuration.nix` configuration file itself is a Nixpkgs Module, so it can be directly added to the `modules` list for use.
Understanding these basics is sufficient for beginners. Exploring the `nixpkgs.lib.nixosSystem` function in detail requires a grasp of the Nixpkgs module system. Understanding these basics is sufficient for beginners. Exploring the `nixpkgs.lib.nixosSystem` function in detail requires a grasp of the Nixpkgs module system.
Readers who have completed the [Modularizing NixOS Configuration](./modularize-the-configuration.md) section can return to [nixpkgs/flake.nix] to find the definition of `nixpkgs.lib.nixosSystem`, trace its source code, and study its implementation. Readers who have completed the [Modularizing NixOS Configuration](./modularize-the-configuration.md) section can return to [nixpkgs/flake.nix] to find the definition of `nixpkgs.lib.nixosSystem`, trace its source code, and study its implementation.
@ -227,7 +224,6 @@ Readers who have completed the [Modularizing NixOS Configuration](./modularize-t
> The detailed workings of this module system will be introduced in the following [Modularizing NixOS Configuration](./modularize-the-configuration.md) section. Here, we'll just cover some basic knowledge. > The detailed workings of this module system will be introduced in the following [Modularizing NixOS Configuration](./modularize-the-configuration.md) section. Here, we'll just cover some basic knowledge.
You might be wondering why the `/etc/nixos/configuration.nix` configuration file adheres to the Nixpkgs Module definition and can be referenced directly within the `flake.nix`. You might be wondering why the `/etc/nixos/configuration.nix` configuration file adheres to the Nixpkgs Module definition and can be referenced directly within the `flake.nix`.
This is because the Nixpkgs repository contains a significant amount of NixOS implementation source code, primarily written in Nix. To manage and maintain such a large volume of Nix code and to allow users to customize various functions of their NixOS systems, a modular system for Nix code is essential. This is because the Nixpkgs repository contains a significant amount of NixOS implementation source code, primarily written in Nix. To manage and maintain such a large volume of Nix code and to allow users to customize various functions of their NixOS systems, a modular system for Nix code is essential.
@ -265,7 +261,6 @@ The definition is actually a Nix function, and it has five **automatically gener
- It is defined in [nixpkgs/nixos/lib/eval-config-minimal.nix#L43](https://github.com/NixOS/nixpkgs/blob/nixos-23.11/nixos/lib/eval-config-minimal.nix#L43). - It is defined in [nixpkgs/nixos/lib/eval-config-minimal.nix#L43](https://github.com/NixOS/nixpkgs/blob/nixos-23.11/nixos/lib/eval-config-minimal.nix#L43).
- It is typically used to import additional NixOS modules and can be found in most NixOS auto-generated `hardware-configuration.nix` files. - It is typically used to import additional NixOS modules and can be found in most NixOS auto-generated `hardware-configuration.nix` files.
## Passing Non-default Parameters to Submodules {#pass-non-default-parameters-to-submodules} ## Passing Non-default Parameters to Submodules {#pass-non-default-parameters-to-submodules}
If you need to pass other non-default parameters to submodules, you will need to use some special methods to manually specify these non-default parameters. If you need to pass other non-default parameters to submodules, you will need to use some special methods to manually specify these non-default parameters.
@ -417,7 +412,6 @@ nix run github:helix-editor/helix/master
We will go into more detail on the usage of `nix run` in the following section [Usage of the New CLI](../other-usage-of-flakes/the-new-cli.md). We will go into more detail on the usage of `nix run` in the following section [Usage of the New CLI](../other-usage-of-flakes/the-new-cli.md).
## Leveraging Features from Other Flakes Packages ## Leveraging Features from Other Flakes Packages
In fact, this is the primary functionality of Flakes — a flake can depend on other flakes, allowing it to utilize the features they provide. It's akin to how we incorporate functionalities from other libraries when writing programs in TypeScript, Go, Rust, and other programming languages. In fact, this is the primary functionality of Flakes — a flake can depend on other flakes, allowing it to utilize the features they provide. It's akin to how we incorporate functionalities from other libraries when writing programs in TypeScript, Go, Rust, and other programming languages.
@ -427,7 +421,6 @@ The example above, using the latest version from the official Helix Flake, illus
- [Getting Started with Home Manager](./start-using-home-manager.md): This introduces the community's Home-Manager as a dependency, enabling direct utilization of the features provided by this Flake. - [Getting Started with Home Manager](./start-using-home-manager.md): This introduces the community's Home-Manager as a dependency, enabling direct utilization of the features provided by this Flake.
- [Downgrading or Upgrading Packages](./downgrade-or-upgrade-packages.md): Here, different versions of Nixpkgs are introduced as dependencies, allowing for flexible selection of packages from various versions of Nixpkgs. - [Downgrading or Upgrading Packages](./downgrade-or-upgrade-packages.md): Here, different versions of Nixpkgs are introduced as dependencies, allowing for flexible selection of packages from various versions of Nixpkgs.
[nixpkgs/flake.nix]: https://github.com/NixOS/nixpkgs/tree/nixos-23.11/flake.nix [nixpkgs/flake.nix]: https://github.com/NixOS/nixpkgs/tree/nixos-23.11/flake.nix
[nixpkgs/nixos/lib/eval-config.nix]: https://github.com/NixOS/nixpkgs/tree/nixos-23.11/nixos/lib/eval-config.nix [nixpkgs/nixos/lib/eval-config.nix]: https://github.com/NixOS/nixpkgs/tree/nixos-23.11/nixos/lib/eval-config.nix
[Module System - Nixpkgs]: https://github.com/NixOS/nixpkgs/blob/23.11/doc/module-system/module-system.chapter.md [Module System - Nixpkgs]: https://github.com/NixOS/nixpkgs/blob/23.11/doc/module-system/module-system.chapter.md

View File

@ -74,7 +74,6 @@ sudo nix profile wipe-history --older-than 7d --profile /nix/var/nix/profiles/sy
sudo nix-collect-garbage --delete-old sudo nix-collect-garbage --delete-old
``` ```
## Why some packages are installed? ## Why some packages are installed?
To find out why a package is installed, you can use the following command: To find out why a package is installed, you can use the following command:
@ -84,7 +83,6 @@ To find out why a package is installed, you can use the following command:
1. `/<package-name>` to find the package you want to check. 1. `/<package-name>` to find the package you want to check.
1. `w` to show the package is depended by which packages, and the full dependency chain. 1. `w` to show the package is depended by which packages, and the full dependency chain.
## Reducing Disk Usage ## Reducing Disk Usage
The following configuration can be added to your NixOS configuration to help reduce disk usage: The following configuration can be added to your NixOS configuration to help reduce disk usage:

View File

@ -251,8 +251,6 @@ The benefits of this approach are:
1. Many configurations in Home Manager are universal for NixOS, macOS, and other Linux distributions. Choosing Home Manager to install software and configure systems can improve the portability of configurations. 1. Many configurations in Home Manager are universal for NixOS, macOS, and other Linux distributions. Choosing Home Manager to install software and configure systems can improve the portability of configurations.
1. If you need multi-user support, software and configurations installed via Home Manager can better isolate different user environments, preventing configuration and software version conflicts between users. 1. If you need multi-user support, software and configurations installed via Home Manager can better isolate different user environments, preventing configuration and software version conflicts between users.
## How to use packages installed by Home Manager with privileged access? ## How to use packages installed by Home Manager with privileged access?
The first thing that comes to mind is to switch to `root`, but then any packages installed by the current user through `home.nix` will be unavailable. The first thing that comes to mind is to switch to `root`, but then any packages installed by the current user through `home.nix` will be unavailable.
@ -285,12 +283,10 @@ Error: nu::shell::external_command
/home/ryan/nix-config> exit /home/ryan/nix-config> exit
``` ```
But it's possible to run those packages with privileged access without switching to `root`, by using `sudo`, we temporarily grant the current user privileged access to system resources: But it's possible to run those packages with privileged access without switching to `root`, by using `sudo`, we temporarily grant the current user privileged access to system resources:
```sh ```sh
sudo kubectl sudo kubectl
kubectl controls the Kubernetes cluster manager. kubectl controls the Kubernetes cluster manager.
... ...
``` ```

View File

@ -32,7 +32,7 @@ While the definition of this Derivation is quite concise, most Derivations in ni
Let's continue to verify this using `nix repl`, and you'll see that the result is still a Derivation: Let's continue to verify this using `nix repl`, and you'll see that the result is still a Derivation:
```shell ```shell
cat hello.nix cat hello.nix
pkgs: pkgs:
pkgs.writeShellScriptBin "hello" '' echo "hello, xxx!" '' pkgs.writeShellScriptBin "hello" '' echo "hello, xxx!" ''
@ -57,7 +57,6 @@ In the previous example without `pkgs.callPackage`, we directly passed `pkgs` as
`pkgs.callPackage`, as a tool for parameterizing the construction of Derivations, addresses these issues. Let's take a look at its source code and comments [nixpkgs/lib/customisation.nix#L101-L121](https://github.com/NixOS/nixpkgs/blob/fe138d3/lib/customisation.nix#L101-L121): `pkgs.callPackage`, as a tool for parameterizing the construction of Derivations, addresses these issues. Let's take a look at its source code and comments [nixpkgs/lib/customisation.nix#L101-L121](https://github.com/NixOS/nixpkgs/blob/fe138d3/lib/customisation.nix#L101-L121):
```nix ```nix
/* Call the package function in the file `fn` with the required /* Call the package function in the file `fn` with the required
arguments automatically. The function is called with the arguments automatically. The function is called with the
@ -87,7 +86,7 @@ In the previous example without `pkgs.callPackage`, we directly passed `pkgs` as
# All arguments that will be passed to the function # All arguments that will be passed to the function
# This includes automatic ones and ones passed explicitly # This includes automatic ones and ones passed explicitly
allArgs = builtins.intersectAttrs fargs autoArgs // args; allArgs = builtins.intersectAttrs fargs autoArgs // args;
# ...... # ......
``` ```
@ -163,4 +162,3 @@ So it's always recommended to use `pkgs.callPackage` to define Derivations.
- [Chapter 13. Callpackage Design Pattern - Nix Pills](https://nixos.org/guides/nix-pills/callpackage-design-pattern.html) - [Chapter 13. Callpackage Design Pattern - Nix Pills](https://nixos.org/guides/nix-pills/callpackage-design-pattern.html)
- [callPackage, a tool for the lazy - The Summer of Nix](https://summer.nixos.org/blog/callpackage-a-tool-for-the-lazy/) - [callPackage, a tool for the lazy - The Summer of Nix](https://summer.nixos.org/blog/callpackage-a-tool-for-the-lazy/)
- [Document what callPackage does and its preconditions - Nixpkgs Issues](https://github.com/NixOS/nixpkgs/issues/36354) - [Document what callPackage does and its preconditions - Nixpkgs Issues](https://github.com/NixOS/nixpkgs/issues/36354)

View File

@ -6,6 +6,7 @@ There are numerous applications for this technique, some common ones include:
1. Instantiate nixpkgs instances with different commit IDs to install various versions of software packages. This approach was used in the previous section [Downgrade or Upgrade Packages](/nixos-with-flakes/downgrade-or-upgrade-packages.md). 1. Instantiate nixpkgs instances with different commit IDs to install various versions of software packages. This approach was used in the previous section [Downgrade or Upgrade Packages](/nixos-with-flakes/downgrade-or-upgrade-packages.md).
2. If you wish to utilize overlays without affecting the default nixpkgs instance, you can instantiate a new nixpkgs instance and apply overlays to it. 2. If you wish to utilize overlays without affecting the default nixpkgs instance, you can instantiate a new nixpkgs instance and apply overlays to it.
- The `nixpkgs.overlays = [...];` mentioned in the previous section on Overlays directly modifies the global nixpkgs instance. If your overlays make changes to some low-level packages, it might impact other modules. One downside is an increase in local compilation (due to cache invalidation), and there might also be functionality issues with the affected packages. - The `nixpkgs.overlays = [...];` mentioned in the previous section on Overlays directly modifies the global nixpkgs instance. If your overlays make changes to some low-level packages, it might impact other modules. One downside is an increase in local compilation (due to cache invalidation), and there might also be functionality issues with the affected packages.
3. In cross-system architecture compilation, you can instantiate multiple nixpkgs instances to selectively use QEMU simulation for compilation and cross-compilation in different locations, or to add various GCC compilation parameters. 3. In cross-system architecture compilation, you can instantiate multiple nixpkgs instances to selectively use QEMU simulation for compilation and cross-compilation in different locations, or to add various GCC compilation parameters.
@ -121,4 +122,3 @@ When creating multiple nixpkgs instances, there are some details to keep in mind
1. According to the article [1000 instances of nixpkgs](https://discourse.nixos.org/t/1000-instances-of-nixpkgs/17347) shared by @fbewivpjsbsby, it's not a good practice to use `import` to customize `nixpkgs` in submodules or sub-flakes. This is because each `import` evaluates separately, creating a new nixpkgs instance each time. As the number of configurations increases, this can lead to longer build times and higher memory usage. Therefore, it's recommended to create all nixpkgs instances in the `flake.nix` file. 1. According to the article [1000 instances of nixpkgs](https://discourse.nixos.org/t/1000-instances-of-nixpkgs/17347) shared by @fbewivpjsbsby, it's not a good practice to use `import` to customize `nixpkgs` in submodules or sub-flakes. This is because each `import` evaluates separately, creating a new nixpkgs instance each time. As the number of configurations increases, this can lead to longer build times and higher memory usage. Therefore, it's recommended to create all nixpkgs instances in the `flake.nix` file.
2. When mixing QEMU simulation and cross-compilation, care should be taken to avoid unnecessary duplication of package compilations. 2. When mixing QEMU simulation and cross-compilation, care should be taken to avoid unnecessary duplication of package compilations.

View File

@ -6,7 +6,7 @@ If the derivation you want to override is also used by other Nix packages, they
To globally modify derivations in the default nixpkgs instance, Nix provides a feature called "overlays". To globally modify derivations in the default nixpkgs instance, Nix provides a feature called "overlays".
In traditional Nix environments, overlays can be configured globally using the `~/.config/nixpkgs/overlays.nix` or `~/.config/nixpkgs/overlays/*.nix` files. In traditional Nix environments, overlays can be configured globally using the `~/.config/nixpkgs/overlays.nix` or `~/.config/nixpkgs/overlays/*.nix` files.
However, with Flakes feature, to ensure system reproducibility, overlays cannot rely on configurations outside of the Git repository. However, with Flakes feature, to ensure system reproducibility, overlays cannot rely on configurations outside of the Git repository.
When using `flake.nix` to configure NixOS, both Home Manager and NixOS provide the `nixpkgs.overlays` option to define overlays. You can refer to the following documentation for more details: When using `flake.nix` to configure NixOS, both Home Manager and NixOS provide the `nixpkgs.overlays` option to define overlays. You can refer to the following documentation for more details:
@ -59,7 +59,7 @@ Let's take a look at an example module that loads overlays. This module can be u
} }
``` ```
In the above example, we define three overlays. In the above example, we define three overlays.
1. Overlay 1 modifies the `google-chrome` derivation by adding a command-line argument for a proxy server. 1. Overlay 1 modifies the `google-chrome` derivation by adding a command-line argument for a proxy server.
2. Overlay 2 modifies the `steam` derivation by adding extra packages and environment variables. 2. Overlay 2 modifies the `steam` derivation by adding extra packages and environment variables.
@ -80,7 +80,7 @@ One example of importing the above configuration as a NixOS module is as follows
system = "x86_64-linux"; system = "x86_64-linux";
modules = [ modules = [
./configuration.nix ./configuration.nix
# import the module that contains overlays # import the module that contains overlays
(import ./overlays) (import ./overlays)
]; ];
@ -92,11 +92,10 @@ One example of importing the above configuration as a NixOS module is as follows
This is just an example. Please write your own overlays according to your needs. This is just an example. Please write your own overlays according to your needs.
## Multiple nixpkgs Instances with different Overlays ## Multiple nixpkgs Instances with different Overlays
The `nixpkgs.overlays = [...];` mentioned above directly modifies the global nixpkgs instance `pkgs`. If your overlays make changes to some low-level packages, it might impact other modules. The `nixpkgs.overlays = [...];` mentioned above directly modifies the global nixpkgs instance `pkgs`. If your overlays make changes to some low-level packages, it might impact other modules.
One downside is an increase in local compilation (due to cache invalidation), One downside is an increase in local compilation (due to cache invalidation),
and there might also be functionality issues with the affected packages. and there might also be functionality issues with the affected packages.
If you wish to utilize overlays only in a specific location without affecting the default nixpkgs instance, you can instantiate a new nixpkgs instance and apply your overlays to it. If you wish to utilize overlays only in a specific location without affecting the default nixpkgs instance, you can instantiate a new nixpkgs instance and apply your overlays to it.

View File

@ -13,8 +13,8 @@ The `inputs` section in `flake.nix` is an attribute set used to specify the depe
# Archive File URL, needed in case your input use LFS. # Archive File URL, needed in case your input use LFS.
# Regular git input doesn't support LFS yet. # Regular git input doesn't support LFS yet.
git-example-lfs.url = "https://codeberg.org/solver-orgz/treedome/archive/master.tar.gz"; git-example-lfs.url = "https://codeberg.org/solver-orgz/treedome/archive/master.tar.gz";
# Similar to fetching a Git repository, but using the ssh protocol # Similar to fetching a Git repository, but using the ssh protocol
# with key authentication. Also uses the shallow=1 parameter # with key authentication. Also uses the shallow=1 parameter
# to avoid copying the .git directory. # to avoid copying the .git directory.
ssh-git-example.url = "git+ssh://git@github.com/ryan4yin/nix-secrets.git?shallow=1"; ssh-git-example.url = "git+ssh://git@github.com/ryan4yin/nix-secrets.git?shallow=1";
# It's also possible to directly depend on a local Git repository. # It's also possible to directly depend on a local Git repository.
@ -39,7 +39,7 @@ The `inputs` section in `flake.nix` is an attribute set used to specify the depe
sops-nix = { sops-nix = {
url = "github:Mic92/sops-nix"; url = "github:Mic92/sops-nix";
# `follows` is the inheritance syntax within inputs. # `follows` is the inheritance syntax within inputs.
# Here, it ensures that sops-nix's `inputs.nixpkgs` aligns with # Here, it ensures that sops-nix's `inputs.nixpkgs` aligns with
# the current flake's inputs.nixpkgs, # the current flake's inputs.nixpkgs,
# avoiding inconsistencies in the dependency's nixpkgs version. # avoiding inconsistencies in the dependency's nixpkgs version.
inputs.nixpkgs.follows = "nixpkgs"; inputs.nixpkgs.follows = "nixpkgs";
@ -55,4 +55,3 @@ The `inputs` section in `flake.nix` is an attribute set used to specify the depe
outputs = { self, ... }@inputs: { ... }; outputs = { self, ... }@inputs: { ... };
} }
``` ```

View File

@ -1,3 +1,3 @@
# Other Usage of Flakes # Other Usage of Flakes
So far, we have extensively used Flakes to manage NixOS configurations. In this section, I will provide a brief introduction to additional features and command-line options commonly used with Flakes. So far, we have extensively used Flakes to manage NixOS configurations. In this section, I will provide a brief introduction to additional features and command-line options commonly used with Flakes.

View File

@ -283,7 +283,7 @@ The first thought might be to directly use `imports` in `config = { ... };`, lik
} }
``` ```
But this won't work. But this won't work.
You can try save the above `flake.nix` in a new directory, and then run `nix eval .#nixosConfigurations.test.config.warnings` in it, some error like `error: The option 'imports' does not exist.` will be encountered. You can try save the above `flake.nix` in a new directory, and then run `nix eval .#nixosConfigurations.test.config.warnings` in it, some error like `error: The option 'imports' does not exist.` will be encountered.
This is because `config` is a regular attribute set, while `imports` is a special parameter of the module system. There is no such definition as `config.imports`. This is because `config` is a regular attribute set, while `imports` is a special parameter of the module system. There is no such definition as `config.imports`.

View File

@ -1,9 +1,7 @@
# Testing # Testing
TODO TODO
## References ## References
- [Integration testing with NixOS virtual machines - nix.dev](https://nix.dev/tutorials/nixos/integration-testing-using-virtual-machines.html) - [Integration testing with NixOS virtual machines - nix.dev](https://nix.dev/tutorials/nixos/integration-testing-using-virtual-machines.html)

View File

@ -1,7 +1,7 @@
# Usage of the New CLI # Usage of the New CLI
Once you have enabled the `nix-command` and `flakes` features, you can start using the new generation Nix command-line tools provided by [New Nix Commands][New Nix Commands]. Once you have enabled the `nix-command` and `flakes` features, you can start using the new generation Nix command-line tools provided by [New Nix Commands][New Nix Commands].
In this section, we will focus on two commands: `nix shell` and `nix run`. In this section, we will focus on two commands: `nix shell` and `nix run`.
Other important commands like `nix build` will be discussed in detail in [`nix develop` & `pkgs.mkShell`](/development/intro.md) Other important commands like `nix build` will be discussed in detail in [`nix develop` & `pkgs.mkShell`](/development/intro.md)
## `nix shell` ## `nix shell`
@ -82,9 +82,8 @@ nix run nixpkgs#git clone git@github.com:ryan4yin/nix-config.git
Alternatively, I can use `nix shell` to enter an environment with Git and then run the `git clone` command: Alternatively, I can use `nix shell` to enter an environment with Git and then run the `git clone` command:
```bash ```bash
nix shell nixpkgs#git nix shell nixpkgs#git
git clone git@github.com:ryan4yin/nix-config.git git clone git@github.com:ryan4yin/nix-config.git
``` ```
[New Nix Commands]: https://nixos.org/manual/nix/stable/command-ref/new-cli/nix.html [New Nix Commands]: https://nixos.org/manual/nix/stable/command-ref/new-cli/nix.html

View File

@ -8,9 +8,9 @@ One of NixOS's major advantages over other distributions lies in its reproducibi
While NixOS is powerful, its strength also comes with increased system complexity. This makes it more challenging for newcomers. One major challenge is that the knowledge accumulated on other Linux distributions is not easily transferable to NixOS. Another is that official and community documentation is often scattered and outdated. These issues have troubled many NixOS beginners. While NixOS is powerful, its strength also comes with increased system complexity. This makes it more challenging for newcomers. One major challenge is that the knowledge accumulated on other Linux distributions is not easily transferable to NixOS. Another is that official and community documentation is often scattered and outdated. These issues have troubled many NixOS beginners.
One can observe these issues with the experimental feature of the Nix package manager called Flakes. Inspired by package managers like npm and Cargo, Flakes uses `flake.nix` to record all external dependencies and `flake.lock` to lock their versions. This significantly enhances the reproducibility and composability of the Nix package manager and NixOS configurations. One can observe these issues with the experimental feature of the Nix package manager called Flakes. Inspired by package managers like npm and Cargo, Flakes uses `flake.nix` to record all external dependencies and `flake.lock` to lock their versions. This significantly enhances the reproducibility and composability of the Nix package manager and NixOS configurations.
Flakes' advantages have made it widely popular within the community: according to official surveys, over half of the new Nix repositories created on GitHub now utilize Flakes. Flakes' advantages have made it widely popular within the community: according to official surveys, over half of the new Nix repositories created on GitHub now utilize Flakes.
However, to maintain stability, the official documentation covers barely any Flakes-related content. This has left many Nix/NixOS users feeling confused. They see everyone using Flakes and want to learn it too, but find nowhere to start, often having to piece together scattered information, search through Nixpkgs source code, or seek help from more experienced users. However, to maintain stability, the official documentation covers barely any Flakes-related content. This has left many Nix/NixOS users feeling confused. They see everyone using Flakes and want to learn it too, but find nowhere to start, often having to piece together scattered information, search through Nixpkgs source code, or seek help from more experienced users.
@ -51,7 +51,7 @@ If you find this book helpful, please consider donating to support its developme
## Feedback and Discussion ## Feedback and Discussion
Im not an expert on NixOS, and Ive only been using NixOS for less than 9 months until now(2024-02), Im not an expert on NixOS, and Ive only been using NixOS for less than 9 months until now(2024-02),
so there must be some misconceptions or complex cases in the book. so there must be some misconceptions or complex cases in the book.
If anyone finds anything incorrect or have any questions / suggestions, just let me know about it by opening an issue or joining the discussion on [GitHub Discussions](https://github.com/ryan4yin/nixos-and-flakes-book/discussions). I'm happy to continue improving the content of this book. If anyone finds anything incorrect or have any questions / suggestions, just let me know about it by opening an issue or joining the discussion on [GitHub Discussions](https://github.com/ryan4yin/nixos-and-flakes-book/discussions). I'm happy to continue improving the content of this book.

View File

@ -1,19 +1,19 @@
{ {
"name": "", "name": "",
"short_name": "", "short_name": "",
"icons": [ "icons": [
{ {
"src": "/android-chrome-192x192.png", "src": "/android-chrome-192x192.png",
"sizes": "192x192", "sizes": "192x192",
"type": "image/png" "type": "image/png"
}, },
{ {
"src": "/android-chrome-512x512.png", "src": "/android-chrome-512x512.png",
"sizes": "512x512", "sizes": "512x512",
"type": "image/png" "type": "image/png"
} }
], ],
"theme_color": "#ffffff", "theme_color": "#ffffff",
"background_color": "#ffffff", "background_color": "#ffffff",
"display": "standalone" "display": "standalone"
} }

View File

@ -4,15 +4,14 @@ The Nix language is essential for declaring configurations to be built by Nix. T
The Nix language is a straightforward functional language. If you have some programming experience, it should take you less than 2 hours to grasp its basics. The Nix language is a straightforward functional language. If you have some programming experience, it should take you less than 2 hours to grasp its basics.
The community already has a lot of good Nix language tutorials, so I won't remake the wheel. The community already has a lot of good Nix language tutorials, so I won't remake the wheel.
To get started, I recommend reading the following resources for a quick introduction to the Nix language: To get started, I recommend reading the following resources for a quick introduction to the Nix language:
1. [**Nix Language Basics - nix.dev**](https://nix.dev/tutorials/first-steps/nix-language): This tutorial provides a comprehensive overview of the basics of the Nix language, recommended for beginners. 1. [**Nix Language Basics - nix.dev**](https://nix.dev/tutorials/first-steps/nix-language): This tutorial provides a comprehensive overview of the basics of the Nix language, recommended for beginners.
1. [**A tour of Nix**](https://nixcloud.io/tour/?id=introduction/nix): An online interactive tutorial focuses on programming language constructs and how Nix can be algorithmically used to solve problems. 1. [**A tour of Nix**](https://nixcloud.io/tour/?id=introduction/nix): An online interactive tutorial focuses on programming language constructs and how Nix can be algorithmically used to solve problems.
3. [**Nix Language - Nix Reference Manual**](https://nixos.org/manual/nix/stable/language/): The official documentation of the Nix language. 1. [**Nix Language - Nix Reference Manual**](https://nixos.org/manual/nix/stable/language/): The official documentation of the Nix language.
1. nix.dev and other user-friendly tutorials are suitable for starter reading only, and **neither of them fully introduces the full syntax of Nix**. If you encounter a new syntax that you have not come across before, please refer to this official document. 1. nix.dev and other user-friendly tutorials are suitable for starter reading only, and **neither of them fully introduces the full syntax of Nix**. If you encounter a new syntax that you have not come across before, please refer to this official document.
3. <https://noogle.dev/> is a Nix function library search engine that can help you quickly find the functions you need and their usage, which is very practical. 1. <https://noogle.dev/> is a Nix function library search engine that can help you quickly find the functions you need and their usage, which is very practical.
It's okay to have a rough impression of the syntax for now. It's okay to have a rough impression of the syntax for now.
You can come back to review the syntax when you find something you don't understand later. You can come back to review the syntax when you find something you don't understand later.

View File

@ -1,6 +1,5 @@
# 进阶玩法 {#advanced-topics} # 进阶玩法 {#advanced-topics}
## 社区 ## 社区
- [Nix 社区官方页](https://nixos.org/community/): 包含官方社区、论坛、RFCs、官方团队的架构以及沟通贡献渠道等信息。 - [Nix 社区官方页](https://nixos.org/community/): 包含官方社区、论坛、RFCs、官方团队的架构以及沟通贡献渠道等信息。
@ -33,7 +32,6 @@
- [Summer of Nix 2022 — Public Lecture Series](https://www.youtube.com/playlist?list=PLt4-_lkyRrOMWyp5G-m_d1wtTcbBaOxZk): NixOS Foundation 举办的一系列公开讲座,由 Eelco Dolstra、Armijn Hemel 等 Nix 社区核心成员主讲,内容涵盖了 Nix 的发展历程、NixOS 的历史、Nix 的未来等多个方面,干货满满。 - [Summer of Nix 2022 — Public Lecture Series](https://www.youtube.com/playlist?list=PLt4-_lkyRrOMWyp5G-m_d1wtTcbBaOxZk): NixOS Foundation 举办的一系列公开讲座,由 Eelco Dolstra、Armijn Hemel 等 Nix 社区核心成员主讲,内容涵盖了 Nix 的发展历程、NixOS 的历史、Nix 的未来等多个方面,干货满满。
- [Summer of Nix 2023 — Nix Developer Dialogues](https://www.youtube.com/playlist?list=PLt4-_lkyRrOPcBuz_tjm6ZQb-6rJjU3cf): 2023 年的 Summer of Nix一系列 Nix 社区核心成员的对话,内容包含 Nixpkgs 的演进与架构方面的挑战,探索 Nix 的模块系统,讨论 Nix 生态Nixpkgs 中的 AI 应用Nix 在商业领域的应用与开源经济学。 - [Summer of Nix 2023 — Nix Developer Dialogues](https://www.youtube.com/playlist?list=PLt4-_lkyRrOPcBuz_tjm6ZQb-6rJjU3cf): 2023 年的 Summer of Nix一系列 Nix 社区核心成员的对话,内容包含 Nixpkgs 的演进与架构方面的挑战,探索 Nix 的模块系统,讨论 Nix 生态Nixpkgs 中的 AI 应用Nix 在商业领域的应用与开源经济学。
另外 @NickCao 在 2021 年做的一个深入介绍 Nix 包管理器的演讲也很值得一阅: 另外 @NickCao 在 2021 年做的一个深入介绍 Nix 包管理器的演讲也很值得一阅:
- [金枪鱼之夜Nix - 从构建系统到配置管理](https://www.bilibili.com/video/BV13Y411p7DS/) - [金枪鱼之夜Nix - 从构建系统到配置管理](https://www.bilibili.com/video/BV13Y411p7DS/)
@ -60,5 +58,3 @@
- ... - ...
想了解更多内容,可以看看 [awesome-nix](https://github.com/nix-community/awesome-nix). 想了解更多内容,可以看看 [awesome-nix](https://github.com/nix-community/awesome-nix).

View File

@ -27,4 +27,3 @@ nvim-test: nvim-clean
测试完毕后,运行下 `just nvim-clean`,再重新用 `nixos-rebuild` 部署下配置,就完成了配置的还原。 测试完毕后,运行下 `just nvim-clean`,再重新用 `nixos-rebuild` 部署下配置,就完成了配置的还原。
这种方法能生效的前提是,你的 Dotfiles 内容不是由 Nix 生成的,比如我的 Emacs/Neovim 配置都是原生的,仅通过 Nix Home-Manager 的 `home.file``xdg.configFile` 将它们链接到正确的位置。 这种方法能生效的前提是,你的 Dotfiles 内容不是由 Nix 生成的,比如我的 Emacs/Neovim 配置都是原生的,仅通过 Nix Home-Manager 的 `home.file``xdg.configFile` 将它们链接到正确的位置。

View File

@ -154,7 +154,6 @@ outputs.nixosConfigurations.ai.config.home-manager.users.ryan.home.file..config/
能看到,通过 `nix repl` 加载好我的 flake 配置后,就能很方便地检查所有的配置项了,这对于调试非常有用。 能看到,通过 `nix repl` 加载好我的 flake 配置后,就能很方便地检查所有的配置项了,这对于调试非常有用。
## 使用 nixpkgs 中提供的调试函数 ## 使用 nixpkgs 中提供的调试函数
TODO TODO
@ -168,5 +167,3 @@ TODO
- [How to make nix build display all commands executed by make?](https://www.reddit.com/r/NixOS/comments/14stdgy/how_to_make_nix_build_display_all_commands/) - [How to make nix build display all commands executed by make?](https://www.reddit.com/r/NixOS/comments/14stdgy/how_to_make_nix_build_display_all_commands/)
- use `NIX_DEBUG=7` in derivation - use `NIX_DEBUG=7` in derivation
- [Collection of functions useful for debugging broken nix expressions.](https://github.com/NixOS/nixpkgs/blob/nixos-23.05/lib/debug.nix) - [Collection of functions useful for debugging broken nix expressions.](https://github.com/NixOS/nixpkgs/blob/nixos-23.05/lib/debug.nix)

View File

@ -1,4 +1,4 @@
# 自定义 NIX_PATH 与 Flake Registry # 自定义 NIX_PATH 与 Flake Registry
## NIX_PATH 介绍 {#nix-path-introduction} ## NIX_PATH 介绍 {#nix-path-introduction}
@ -18,7 +18,6 @@ Flake Registry 是一个 Flake 注册中心,它可以帮助我们在使用 `ni
比如说我们执行 `nix run nixpkgs#ponysay hello`nix 会自动从上述 json 文件中找到 `nixpkgs` 对应的 github 仓库地址,然后下载这个仓库,再通过其中的 `flake.nix` 查找对应的 `ponysay` 包并运行它。 比如说我们执行 `nix run nixpkgs#ponysay hello`nix 会自动从上述 json 文件中找到 `nixpkgs` 对应的 github 仓库地址,然后下载这个仓库,再通过其中的 `flake.nix` 查找对应的 `ponysay` 包并运行它。
## 自定义 NIX_PATH 与 Flake Registry {#custom-nix-path-and-flake-registry-2} ## 自定义 NIX_PATH 与 Flake Registry {#custom-nix-path-and-flake-registry-2}
> **注意:新手请先跳过这部分内容!因为配置如果抄得不对,关掉 nix-channel 可能会导致一些令人头疼的错误。** > **注意:新手请先跳过这部分内容!因为配置如果抄得不对,关掉 nix-channel 可能会导致一些令人头疼的错误。**
@ -46,4 +45,3 @@ Flake Registry 是一个 Flake 注册中心,它可以帮助我们在使用 `ni
## 参考 ## 参考
- [Chapter 15. Nix Search Paths - Nix Pills](https://nixos.org/guides/nix-pills/nix-search-paths.html) - [Chapter 15. Nix Search Paths - Nix Pills](https://nixos.org/guides/nix-pills/nix-search-paths.html)

View File

@ -14,15 +14,15 @@ Nix 本身的设计就很适合远程部署Nix 社区也有许多专门用于
在进行远程部署之前,需要做一些准备工作: 在进行远程部署之前,需要做一些准备工作:
1. 为了防止远程主机的 sudo 密码验证失败,有两种方法,二选一: 1. 为了防止远程主机的 sudo 密码验证失败,有两种方法,二选一:
1. 以远程主机的 `root` 用户身份部署,这是推荐使用的方法。 1. 以远程主机的 `root` 用户身份部署,这是推荐使用的方法。
2. 在远程主机的配置中添加 `security.sudo.wheelNeedsPassword = false;` 并提前手动部署一次,从而为用户授予免密码验证的 sudo 权限。 2. 在远程主机的配置中添加 `security.sudo.wheelNeedsPassword = false;` 并提前手动部署一次,从而为用户授予免密码验证的 sudo 权限。
1. **这会导致用户级别的程序能静默获取 sudo 权限,存在安全风险**!因此如果选用这种方法,建议远程部署创建一个专门的用户,不应该使用自己的常用用户! 1. **这会导致用户级别的程序能静默获取 sudo 权限,存在安全风险**!因此如果选用这种方法,建议远程部署创建一个专门的用户,不应该使用自己的常用用户!
2. 为远程主机配置 SSH 公钥身份验证 2. 为远程主机配置 SSH 公钥身份验证
1. 可使用 `users.users.<name>.openssh.authorizedKeys.keys` 配置项完成配置。 1. 可使用 `users.users.<name>.openssh.authorizedKeys.keys` 配置项完成配置。
1. 在本机主机上添加好远程主机的 Known Hosts 记录,否则 colmena/nixos-rebuild 会因为无法验证远程主机的身份而部署失败。 3. 在本机主机上添加好远程主机的 Known Hosts 记录,否则 colmena/nixos-rebuild 会因为无法验证远程主机的身份而部署失败。
1. 可使用 `programs.ssh.knownHosts` 配置项将远程主机的公钥添加到 Known Hosts 记录中。 1. 可使用 `programs.ssh.knownHosts` 配置项将远程主机的公钥添加到 Known Hosts 记录中。
1. 手动使用 `ssh root@<you-host>` 命令,验证能正常登录到远程主机。 4. 手动使用 `ssh root@<you-host>` 命令,验证能正常登录到远程主机。
1. 如果遇到任何问题,请先解决它们,再继续后续操作。 1. 如果遇到任何问题,请先解决它们,再继续后续操作。
建议使用 `root` 用户进行部署,因为这更方便且不需要额外的配置,没有令人头疼的 sudo 权限问题。 建议使用 `root` 用户进行部署,因为这更方便且不需要额外的配置,没有令人头疼的 sudo 权限问题。
@ -99,7 +99,7 @@ ssh-add ~/.ssh/your-private-key
现在,您可以将配置部署到设备上: 现在,您可以将配置部署到设备上:
```bash ```bash
nix run nixpkgs#colmena apply nix run nixpkgs#colmena apply
``` ```
更复杂的用法,请参阅 colmena 的官方文档 <https://colmena.cli.rs/unstable/introduction.html> 更复杂的用法,请参阅 colmena 的官方文档 <https://colmena.cli.rs/unstable/introduction.html>
@ -140,4 +140,3 @@ Host aquamarine
```bash ```bash
nixos-rebuild switch --flake .#my-nixos --target-host root@aquamarine --build-host root@aquamarine --verbose nixos-rebuild switch --flake .#my-nixos --target-host root@aquamarine --build-host root@aquamarine --verbose
``` ```

View File

@ -55,12 +55,11 @@ source ./env/bin/activate
这当然是可行的,有现成的 Nix 封装工具帮我们干这个活: 这当然是可行的,有现成的 Nix 封装工具帮我们干这个活:
> 注意即使是在这俩环境中,直接跑 `pip install` 之类的安装命令仍然是会失败的,必须通过 `flake.nix` 来安装 Python 依赖! > 注意即使是在这俩环境中,直接跑 `pip install` 之类的安装命令仍然是会失败的,必须通过 `flake.nix` 来安装 Python 依赖!
因为数据还是在 `/nix/store` 中,这类修改命令必须在 Nix 的构建阶段才能执行... > 因为数据还是在 `/nix/store` 中,这类修改命令必须在 Nix 的构建阶段才能执行...
- [DavHau/mach-nix](https://github.com/DavHau/mach-nix) - [DavHau/mach-nix](https://github.com/DavHau/mach-nix)
- [poetry2nix](https://github.com/nix-community/poetry2nix) - [poetry2nix](https://github.com/nix-community/poetry2nix)
这俩工具的好处是,能利用上 Nix Flakes 的锁机制来提升可复现能力,缺点是多了一层封装,底层变得更复杂了。 这俩工具的好处是,能利用上 Nix Flakes 的锁机制来提升可复现能力,缺点是多了一层封装,底层变得更复杂了。
最后,在一些更复杂的项目上,上述两种方案可能都行不通,这时候最佳的解决方案,就是改用容器了,比如 Docker、Podman 等,容器的限制没 Nix 这么严格,能提供最佳的兼容性。 最后,在一些更复杂的项目上,上述两种方案可能都行不通,这时候最佳的解决方案,就是改用容器了,比如 Docker、Podman 等,容器的限制没 Nix 这么严格,能提供最佳的兼容性。

View File

@ -116,6 +116,3 @@ stdenv.mkDerivation (finalAttrs: {
}; };
}) })
``` ```

View File

@ -23,7 +23,7 @@ Nix 与 Ansible 这类被广泛应用的传统工具比,主要优势就在:
1. Ansible 这类工具一个最大的问题就是,它每次部署都是基于系统当前状态的增量修改。而系统的当前状态就如同前面提到的系统快照,是不可解释的,也很难复现。而 NixOS 是通过配置文件声明系统的目标状态,可以做到部署结果与系统当前状态无关,重复部署也不会导致任何问题。 1. Ansible 这类工具一个最大的问题就是,它每次部署都是基于系统当前状态的增量修改。而系统的当前状态就如同前面提到的系统快照,是不可解释的,也很难复现。而 NixOS 是通过配置文件声明系统的目标状态,可以做到部署结果与系统当前状态无关,重复部署也不会导致任何问题。
2. Nix Flakes 通过一个版本锁文件 `flake.lock` 锁定了所有依赖的 hash 值、版本号、数据源等信息,这极大地提升了系统的可复现能力。而传统的 Ansible 等工具没有此功能,所以它们的可复现能力很差。 2. Nix Flakes 通过一个版本锁文件 `flake.lock` 锁定了所有依赖的 hash 值、版本号、数据源等信息,这极大地提升了系统的可复现能力。而传统的 Ansible 等工具没有此功能,所以它们的可复现能力很差。
1. 这也是为什么 Docker 这么受欢迎的原因——它以较低的代价提供了 Ansible 等传统运维工具提供不了的**可在各种机器上复现的系统环境**。 1. 这也是为什么 Docker 这么受欢迎的原因——它以较低的代价提供了 Ansible 等传统运维工具提供不了的**可在各种机器上复现的系统环境**。
1. Nix 通过一层声明式的抽象屏蔽了其底层的实现细节,使用户只需要关心自己最核心的需求,从而带来了高度便捷的系统自定义能力。而 Ansible 这类工具的抽象能力要弱得多。 3. Nix 通过一层声明式的抽象屏蔽了其底层的实现细节,使用户只需要关心自己最核心的需求,从而带来了高度便捷的系统自定义能力。而 Ansible 这类工具的抽象能力要弱得多。
1. 如果你有使用过 terraform/kubernetes 等声明式配置工具,应该很容易理解这一点。需求越是复杂的情况下,声明式配置带来的好处就越大。 1. 如果你有使用过 terraform/kubernetes 等声明式配置工具,应该很容易理解这一点。需求越是复杂的情况下,声明式配置带来的好处就越大。
## Nix 与 Docker 容器技术相比有何优势? ## Nix 与 Docker 容器技术相比有何优势?
@ -77,7 +77,7 @@ Nix 与以 Docker 为代表的容器技术的应用场景也存在一定重合
```bash ```bash
error: builder for '/nix/store/n3scj3s7v9jsb6y3v0fhndw35a9hdbs6-home-manager-path.drv' failed with exit code 25; error: builder for '/nix/store/n3scj3s7v9jsb6y3v0fhndw35a9hdbs6-home-manager-path.drv' failed with exit code 25;
last 1 log lines: last 1 log lines:
> error: collision between `/nix/store/kvq0gvz6jwggarrcn9a8ramsfhyh1h9d-lldb-14.0.6/lib/python3.11/site-packages/six.py' > 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' 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'. For full logs, run 'nix log /nix/store/n3scj3s7v9jsb6y3v0fhndw35a9hdbs6-home-manager-path.drv'.
``` ```
@ -86,34 +86,33 @@ and `/nix/store/370s8inz4fc9k9lqk4qzj5vyr60q166w-python3-3.11.6-env/lib/python3.
1. 将两个包拆分到两个不同的 **profiles** 中。比如说,你可以通过 `environment.systemPackages` 安装 `lldb`,通过 `home.packages` 安装 `python311` 1. 将两个包拆分到两个不同的 **profiles** 中。比如说,你可以通过 `environment.systemPackages` 安装 `lldb`,通过 `home.packages` 安装 `python311`
2. 不同版本的 Python3 被视为不同的包,所以你可以将你的自定义 Python3 版本改为 `python310` 以避免冲突。 2. 不同版本的 Python3 被视为不同的包,所以你可以将你的自定义 Python3 版本改为 `python310` 以避免冲突。
2. 使用 `override` 来覆盖包使用的库的版本,使其与另一个包使用的版本一致。 3. 使用 `override` 来覆盖包使用的库的版本,使其与另一个包使用的版本一致。
```nix ```nix
{ {
# as a nixos module # as a nixos module
# environment.systemPackages = with pkgs; [ # environment.systemPackages = with pkgs; [
# #
# or as a home manager module # or as a home manager module
home.packages = let home.packages = let
custom-python3 = (pkgs.python311.withPackages (ps: custom-python3 = (pkgs.python311.withPackages (ps:
with ps; [ with ps; [
ipython ipython
pandas pandas
requests requests
pyquery pyquery
pyyaml pyyaml
] ]
)); ));
in in
with pkgs; [ with pkgs; [
# override the version of python3 # override the version of python3
# NOTE: This will trigger a rebuild of lldb, it takes time # NOTE: This will trigger a rebuild of lldb, it takes time
(lldb.override { (lldb.override {
python3 = custom-python3; python3 = custom-python3;
}) })
custom-python3
];
}
```
custom-python3
];
}
```

View File

@ -29,6 +29,7 @@ hero:
# - title: Feature C # - title: Feature C
# details: Lorem ipsum dolor sit amet, consectetur adipiscing elit # details: Lorem ipsum dolor sit amet, consectetur adipiscing elit
--- ---
<style> <style>
:root { :root {
--vp-home-hero-name-color: transparent; --vp-home-hero-name-color: transparent;

View File

@ -31,20 +31,18 @@ Nix 是一个声明式的软件包管理器,用户需要通过某些配置声
切换到 NixOS 后,我对它那是相当的满意,腰也不疼了,背也不酸了... 切换到 NixOS 后,我对它那是相当的满意,腰也不疼了,背也不酸了...
最惊艳的是,现在我可以通过仅仅一行命令(`sudo nixos-rebuild switch --flake .`),就能在一台全新安装的 NixOS 主机上还原我的整个 i3 桌面环境以及所有我的常用软件! 最惊艳的是,现在我可以通过仅仅一行命令(`sudo nixos-rebuild switch --flake .`),就能在一台全新安装的 NixOS 主机上还原我的整个 i3 桌面环境以及所有我的常用软件!
NixOS 的回滚能力与可复现能力给了我非常大的底气,我现在再也不用怕把系统搞挂了(挂了直接回滚就恢复了),于是我又在 NixOS 尝试了 Hyprland, Waybar 等等许多新鲜玩意儿~ NixOS 的回滚能力与可复现能力给了我非常大的底气,我现在再也不用怕把系统搞挂了(挂了直接回滚就恢复了),于是我又在 NixOS 尝试了 Hyprland, Waybar 等等许多新鲜玩意儿~
在以前 EndeavourOS 上我肯定是不太敢这么玩的,因为万一要是把系统玩出毛病了,就必须手动排查问题、修复系统状态,那可是相当麻烦。 在以前 EndeavourOS 上我肯定是不太敢这么玩的,因为万一要是把系统玩出毛病了,就必须手动排查问题、修复系统状态,那可是相当麻烦。
随着我对 NixOS 与 Nix 的使用越来越深入,我发现它还非常适合用于同步管理多台主机的配置。 随着我对 NixOS 与 Nix 的使用越来越深入,我发现它还非常适合用于同步管理多台主机的配置。
目前我的个人配置 [ryan4yin/nix-config](https://github.com/ryan4yin/nix-config) 同步管理了许多主机的配置: 目前我的个人配置 [ryan4yin/nix-config](https://github.com/ryan4yin/nix-config) 同步管理了许多主机的配置:
- 桌面电脑 - 桌面电脑
- 一台 Macbook Pro 2020 (Intel amd64) - 一台 Macbook Pro 2020 (Intel amd64)
- 一台 Macbook Pro 2022 (M2 aarch64) - 一台 Macbook Pro 2022 (M2 aarch64)
- 一台 NixOS 桌面 PC (amd64) - 一台 NixOS 桌面 PC (amd64)
- 服务器 - 服务器
- 三台 NixOS 虚拟机(amd64) - 三台 NixOS 虚拟机(amd64)
- 若干块 aarch64 跟 riscv64 的开发板 - 若干块 aarch64 跟 riscv64 的开发板
其中三台桌面电脑的开发环境都通过 Home Manager 管理,主要配置完全共用,在任意一台主机上修改的配置,可以通过 Git 无缝同步到其他主机上。NixOS 几乎完全帮我屏蔽了三台机器底层的 OS 与芯片架构差异,体验非常丝滑! 其中三台桌面电脑的开发环境都通过 Home Manager 管理,主要配置完全共用,在任意一台主机上修改的配置,可以通过 Git 无缝同步到其他主机上。NixOS 几乎完全帮我屏蔽了三台机器底层的 OS 与芯片架构差异,体验非常丝滑!

View File

@ -14,7 +14,6 @@ NixOS 的安装步骤很简单,这里不多介绍,仅列一下我觉得比
1. [复用 flake 管理 NixOS WSL](https://zhuanlan.zhihu.com/p/627073511): 使用 WSL 的用户可以参考下这篇文章 1. [复用 flake 管理 NixOS WSL](https://zhuanlan.zhihu.com/p/627073511): 使用 WSL 的用户可以参考下这篇文章
1. [ryan4yin/nix-darwin-kickstarter](https://github.com/ryan4yin/nix-darwin-kickstart): macOS 用户可以通过这个模板仓库结合本书的内容来学习使用 Nix. 1. [ryan4yin/nix-darwin-kickstarter](https://github.com/ryan4yin/nix-darwin-kickstart): macOS 用户可以通过这个模板仓库结合本书的内容来学习使用 Nix.
## 对中国大陆用户流畅使用 NixOS 的建议 ## 对中国大陆用户流畅使用 NixOS 的建议
国内用户在使用 NixOS 时会存在一些网络问题,一是 NixOS 高度依赖 GitHub 作为 channel/flake 数据源——在国内访问 GitHub 相当的慢,二是 NixOS 官方的包缓存服务器在国内访问速度较慢。 国内用户在使用 NixOS 时会存在一些网络问题,一是 NixOS 高度依赖 GitHub 作为 channel/flake 数据源——在国内访问 GitHub 相当的慢,二是 NixOS 官方的包缓存服务器在国内访问速度较慢。
@ -23,7 +22,6 @@ NixOS 的安装步骤很简单,这里不多介绍,仅列一下我觉得比
这里我先介绍几个比较简单的配置方法。 这里我先介绍几个比较简单的配置方法。
### 1. 包缓存服务器的加速访问 ### 1. 包缓存服务器的加速访问
首先,在执行后面给出的任何 `nix` 相关命令时,你都可以通过 `--option` 选项来指定镜像源,例如: 首先,在执行后面给出的任何 `nix` 相关命令时,你都可以通过 `--option` 选项来指定镜像源,例如:
@ -47,7 +45,6 @@ nix shell nixpkgs#cowsay --option substituters "https://mirrors.tuna.tsinghua.ed
你可以自己测试下上述几个镜像源的速度,选速度最快的一个。 你可以自己测试下上述几个镜像源的速度,选速度最快的一个。
### 2. Channel/Flake 的加速访问 ### 2. Channel/Flake 的加速访问
对于 Flake Inputs 跟 Channels 的加速访问,这个就需要使用代理工具加速访问。 对于 Flake Inputs 跟 Channels 的加速访问,这个就需要使用代理工具加速访问。

View File

@ -229,7 +229,7 @@ Nix 提供了 [`extra-` 前缀](https://nixos.org/manual/nix/stable/command-ref/
} }
``` ```
## 通过代理加速包下载 {#accelerate-package-downloads-via-a-proxy-server} ## 通过代理加速包下载 {#accelerate-package-downloads-via-a-proxy-server}
> 参考了 Issue: [roaming laptop: network proxy configuration - NixOS/nixpkgs](https://github.com/NixOS/nixpkgs/issues/27535#issuecomment-1178444327) > 参考了 Issue: [roaming laptop: network proxy configuration - NixOS/nixpkgs](https://github.com/NixOS/nixpkgs/issues/27535#issuecomment-1178444327)
@ -270,6 +270,5 @@ sudo systemctl restart nix-daemon
位于 `/run/systemd/system/nix-daemon.service.d/override.conf` 的设置会在系统重启后被自动删除,或者你可以手动删除它并重启 nix-daemon 服务来恢复原始设置。 位于 `/run/systemd/system/nix-daemon.service.d/override.conf` 的设置会在系统重启后被自动删除,或者你可以手动删除它并重启 nix-daemon 服务来恢复原始设置。
> 使用一些商用代理或公共代理时你可能会遇到 GitHub 下载时报 HTTP 403 错误([nixos-and-flakes-book/issues/74](https://github.com/ryan4yin/nixos-and-flakes-book/issues/74) > 使用一些商用代理或公共代理时你可能会遇到 GitHub 下载时报 HTTP 403 错误([nixos-and-flakes-book/issues/74](https://github.com/ryan4yin/nixos-and-flakes-book/issues/74)
> 可尝试通过更换代理服务器或者设置 [access-tokens](https://github.com/NixOS/nix/issues/6536) 来解决。 > 可尝试通过更换代理服务器或者设置 [access-tokens](https://github.com/NixOS/nix/issues/6536) 来解决。

View File

@ -49,7 +49,6 @@ Flakes 带来的好处是显而易见的,整个 NixOS 社区都很喜欢它,
读完上述内容后,个人猜测,**Flakes 有可能(仅是可能)会在未来两年内成为稳定特性**。 读完上述内容后,个人猜测,**Flakes 有可能(仅是可能)会在未来两年内成为稳定特性**。
## Nix 的新 CLI 与旧的 CLI {#the-new-cli-and-the-classic-cli} ## Nix 的新 CLI 与旧的 CLI {#the-new-cli-and-the-classic-cli}
Nix 于 2020 年推出了 `nix-command` & `flakes` 两个实验特性,它们提供了全新的命令行工具(即 New CLI、标准的 Nix 包结构定义(即 Flakes 特性)、类似 cargo/npm 的 `flake.lock` 版本锁文件等等。这两个特性极大地增强了 Nix 的能力因此虽然至今2024/2/1它们仍然是实验性特性但是已经被 Nix 社区广泛使用。 Nix 于 2020 年推出了 `nix-command` & `flakes` 两个实验特性,它们提供了全新的命令行工具(即 New CLI、标准的 Nix 包结构定义(即 Flakes 特性)、类似 cargo/npm 的 `flake.lock` 版本锁文件等等。这两个特性极大地增强了 Nix 的能力因此虽然至今2024/2/1它们仍然是实验性特性但是已经被 Nix 社区广泛使用。
@ -74,7 +73,6 @@ Nix 于 2020 年推出了 `nix-command` & `flakes` 两个实验特性,它们
6. 以及其他使用地较少的命令,就不一一列出了. 6. 以及其他使用地较少的命令,就不一一列出了.
1. 详细的命令对比列表可以看看 [Try to explain nix commands](https://qiita-com.translate.goog/Sumi-Sumi/items/6de9ee7aab10bc0dbead?_x_tr_sl=auto&_x_tr_tl=en&_x_tr_hl=en) 1. 详细的命令对比列表可以看看 [Try to explain nix commands](https://qiita-com.translate.goog/Sumi-Sumi/items/6de9ee7aab10bc0dbead?_x_tr_sl=auto&_x_tr_tl=en&_x_tr_hl=en)
[^1]: [Flakes - NixOS Wiki](https://nixos.wiki/index.php?title=Flakes) [^1]: [Flakes - NixOS Wiki](https://nixos.wiki/index.php?title=Flakes)
[^2]: [Flakes are such an obviously good thing](https://grahamc.com/blog/flakes-are-an-obviously-good-thing/) [^2]: [Flakes are such an obviously good thing](https://grahamc.com/blog/flakes-are-an-obviously-good-thing/)
[^3]: [Draft: 1 year roadmap - NixOS Foundation](https://nixos-foundation.notion.site/1-year-roadmap-0dc5c2ec265a477ea65c549cd5e568a9) [^3]: [Draft: 1 year roadmap - NixOS Foundation](https://nixos-foundation.notion.site/1-year-roadmap-0dc5c2ec265a477ea65c549cd5e568a9)

View File

@ -256,20 +256,19 @@ echo 'insert after default'
" "
# 示例二:单行字符串合并 # 示例二:单行字符串合并
echo $(nix eval .#nixosConfigurations.my-nixos.config.programs.zsh.shellInit) echo $(nix eval .#nixosConfigurations.my-nixos.config.programs.zsh.shellInit)
"echo 'insert before default'; "echo 'insert before default';
echo 'this is default'; echo 'this is default';
echo 'insert after default';" echo 'insert after default';"
# 示例三:列表合并 # 示例三:列表合并
nix eval .#nixosConfigurations.my-nixos.config.nix.settings.substituters nix eval .#nixosConfigurations.my-nixos.config.nix.settings.substituters
[ "https://nix-community.cachix.org" "https://nix-community.cachix.org" "https://cache.nixos.org/" "https://ryan4yin.cachix.org" ] [ "https://nix-community.cachix.org" "https://nix-community.cachix.org" "https://cache.nixos.org/" "https://ryan4yin.cachix.org" ]
``` ```
可以看到,`lib.mkBefore` 会将后面的值插入到前面,而 `lib.mkAfter` 会将后面的值插入到前面。 可以看到,`lib.mkBefore` 会将后面的值插入到前面,而 `lib.mkAfter` 会将后面的值插入到前面。
> 对模块系统更深入的介绍,参见 [模块系统与自定义 options](../other-usage-of-flakes/module-system.md). > 对模块系统更深入的介绍,参见 [模块系统与自定义 options](../other-usage-of-flakes/module-system.md).
## References ## References

View File

@ -218,7 +218,6 @@ sudo nixos-rebuild switch --flake github:owner/repo#your-hostname
新手阶段了解这些就足够了,探究 `nixpkgs.lib.nixosSystem` 函数的具体实现需要对 Nixpkgs 的模块系统有一定的了解。 新手阶段了解这些就足够了,探究 `nixpkgs.lib.nixosSystem` 函数的具体实现需要对 Nixpkgs 的模块系统有一定的了解。
读者可以在学习了 [模块化 NixOS 配置](./modularize-the-configuration.md) 一节后,再回过头来从 [nixpkgs/flake.nix] 中找到 `nixpkgs.lib.nixosSystem` 的定义,跟踪它的源码,研究其实现方式。 读者可以在学习了 [模块化 NixOS 配置](./modularize-the-configuration.md) 一节后,再回过头来从 [nixpkgs/flake.nix] 中找到 `nixpkgs.lib.nixosSystem` 的定义,跟踪它的源码,研究其实现方式。
## Nixpkgs Module 结构的简单介绍 {#simple-introduction-to-nixpkgs-module-structure} ## Nixpkgs Module 结构的简单介绍 {#simple-introduction-to-nixpkgs-module-structure}
> 在后面的 [模块化 NixOS 配置](./modularize-the-configuration.md) 一节中会详细介绍这套模块系统的工作方式,这里只介绍些基础知识。 > 在后面的 [模块化 NixOS 配置](./modularize-the-configuration.md) 一节中会详细介绍这套模块系统的工作方式,这里只介绍些基础知识。
@ -430,7 +429,6 @@ nix run github:helix-editor/helix/master
- [Getting Started with Home Manager](./start-using-home-manager.md): 这里引入了社区的 Home-Manager 作为依赖项,从而能直接使用该 Flake 提供的功能。 - [Getting Started with Home Manager](./start-using-home-manager.md): 这里引入了社区的 Home-Manager 作为依赖项,从而能直接使用该 Flake 提供的功能。
- [Downgrading or Upgrading Packages](./downgrade-or-upgrade-packages.md): 这里引入了不同版本的 Nixpkgs 作为依赖项,从而能很灵活地选用不同版本的 Nixpkgs 中的包。 - [Downgrading or Upgrading Packages](./downgrade-or-upgrade-packages.md): 这里引入了不同版本的 Nixpkgs 作为依赖项,从而能很灵活地选用不同版本的 Nixpkgs 中的包。
[nixpkgs/flake.nix]: https://github.com/NixOS/nixpkgs/tree/nixos-23.11/flake.nix [nixpkgs/flake.nix]: https://github.com/NixOS/nixpkgs/tree/nixos-23.11/flake.nix
[nixpkgs/nixos/lib/eval-config.nix]: https://github.com/NixOS/nixpkgs/tree/nixos-23.11/nixos/lib/eval-config.nix [nixpkgs/nixos/lib/eval-config.nix]: https://github.com/NixOS/nixpkgs/tree/nixos-23.11/nixos/lib/eval-config.nix
[Module System - Nixpkgs]: https://github.com/NixOS/nixpkgs/blob/23.11/doc/module-system/module-system.chapter.md [Module System - Nixpkgs]: https://github.com/NixOS/nixpkgs/blob/23.11/doc/module-system/module-system.chapter.md

View File

@ -80,7 +80,6 @@ sudo nix-collect-garbage --delete-old
1. `/<package-name>` 以查找到你想查询的包 1. `/<package-name>` 以查找到你想查询的包
1. 输入 `w`,看看谁依赖了它(`why depends`),以及完整的依赖链。 1. 输入 `w`,看看谁依赖了它(`why depends`),以及完整的依赖链。
## 节约存储空间 ## 节约存储空间
如下配置可以比较好的缩减 NixOS 的磁盘占用,可以考虑将它们添加到你的 NixOS 配置中: 如下配置可以比较好的缩减 NixOS 的磁盘占用,可以考虑将它们添加到你的 NixOS 配置中:

View File

@ -254,7 +254,6 @@ nix flake new example -t github:nix-community/home-manager#nixos
1. Home Manager 的许多配置都可以在 NixOS, macOS 以及其他 Linux 发行版上通用,尽可能选用 Home Manager 来安装软件与配置系统,可以提高配置的可移植性。 1. Home Manager 的许多配置都可以在 NixOS, macOS 以及其他 Linux 发行版上通用,尽可能选用 Home Manager 来安装软件与配置系统,可以提高配置的可移植性。
1. 如果你需要多用户,通过 Home Manager 安装的软件与配置,可以更好地隔离不同用户的环境,避免不同用户之间的配置与软件版本冲突。 1. 如果你需要多用户,通过 Home Manager 安装的软件与配置,可以更好地隔离不同用户的环境,避免不同用户之间的配置与软件版本冲突。
## 如何以特权身份使用 Home Manager 安装的软件包? ## 如何以特权身份使用 Home Manager 安装的软件包?
对这个问题,首先想到的一般都是直接切换到 `root` 用户, 可切换用户后,当前用户通过 `home.nix` 安装的软件包都将不可用。 对这个问题,首先想到的一般都是直接切换到 `root` 用户, 可切换用户后,当前用户通过 `home.nix` 安装的软件包都将不可用。
@ -294,5 +293,3 @@ Error: nu::shell::external_command
kubectl controls the Kubernetes cluster manager. kubectl controls the Kubernetes cluster manager.
... ...
``` ```

View File

@ -27,13 +27,13 @@ nix-repl> pkgs.writeShellScriptBin "hello" '' echo "hello, xxx!" ''
前面我们介绍并大量使用了 `import xxx.nix` 来从其他 Nix 文件中导入 Nix 表达式,我们可以在这里也使用这种方法来提升代码的可维护性: 前面我们介绍并大量使用了 `import xxx.nix` 来从其他 Nix 文件中导入 Nix 表达式,我们可以在这里也使用这种方法来提升代码的可维护性:
1. 将上面这一行 Derivation 的定义存放到单独的文件 `hello.nix` 中。 1. 将上面这一行 Derivation 的定义存放到单独的文件 `hello.nix` 中。
1. 但 `hello.nix` 自身的上下文中不包含 `pkgs` 这个变量,所以需要修改下其内容,将 `pkgs` 作为参数传递给 `hello.nix` 1. 但 `hello.nix` 自身的上下文中不包含 `pkgs` 这个变量,所以需要修改下其内容,将 `pkgs` 作为参数传递给 `hello.nix`
1. 在需要使用这个 Derivation 的地方,使用 `import ./hello.nix pkgs` 来导入它并使用 `pkgs` 作为参数来执行其中定义的函数。 1. 在需要使用这个 Derivation 的地方,使用 `import ./hello.nix pkgs` 来导入它并使用 `pkgs` 作为参数来执行其中定义的函数。
仍然使用 `nix repl` 来验证一下,能看到它的执行结果仍然是一个 Derivation 仍然使用 `nix repl` 来验证一下,能看到它的执行结果仍然是一个 Derivation
```shell ```shell
cat hello.nix cat hello.nix
pkgs: pkgs:
pkgs.writeShellScriptBin "hello" '' echo "hello, xxx!" '' pkgs.writeShellScriptBin "hello" '' echo "hello, xxx!" ''
@ -53,12 +53,11 @@ nix-repl> import ./hello.nix pkgs
在前面不使用 `pkgs.callPackage` 的例子中,我们直接将 `pkgs` 作为参数传到了 `hello.nix` 中,这样做的缺点有: 在前面不使用 `pkgs.callPackage` 的例子中,我们直接将 `pkgs` 作为参数传到了 `hello.nix` 中,这样做的缺点有:
1. `hello` 这个 derivation 的所有其他依赖项都只能从 `pkgs` 中获取,耦合度太高。 1. `hello` 这个 derivation 的所有其他依赖项都只能从 `pkgs` 中获取,耦合度太高。
1. 比如说我们如果需要其他自定义依赖项,就必须修改 `pkgs` 或者修改 `hello.nix` 的内容,而这两个都很麻烦。 1. 比如说我们如果需要其他自定义依赖项,就必须修改 `pkgs` 或者修改 `hello.nix` 的内容,而这两个都很麻烦。
1. 在 `hello.nix` 变复杂的情况下,很难判断 `hello.nix` 到底依赖了 `pkgs` 中的哪些 Derivation很难分析 Derivation 之间的依赖关系。 1. 在 `hello.nix` 变复杂的情况下,很难判断 `hello.nix` 到底依赖了 `pkgs` 中的哪些 Derivation很难分析 Derivation 之间的依赖关系。
`pkgs.callPackage` 作为一个参数化构建 Derivation 的工具函数,可解决上述两个问题。 `pkgs.callPackage` 作为一个参数化构建 Derivation 的工具函数,可解决上述两个问题。
首先看看源码中此函数的定义与注释 [nixpkgs/lib/customisation.nix#L101-L121](https://github.com/NixOS/nixpkgs/blob/fe138d3/lib/customisation.nix#L101-L121 首先看看源码中此函数的定义与注释 [nixpkgs/lib/customisation.nix#L101-L121](https://github.com/NixOS/nixpkgs/blob/fe138d3/lib/customisation.nix#L101-L121)
)
```nix ```nix
/* Call the package function in the file `fn` with the required /* Call the package function in the file `fn` with the required
@ -89,7 +88,7 @@ nix-repl> import ./hello.nix pkgs
# All arguments that will be passed to the function # All arguments that will be passed to the function
# This includes automatic ones and ones passed explicitly # This includes automatic ones and ones passed explicitly
allArgs = builtins.intersectAttrs fargs autoArgs // args; allArgs = builtins.intersectAttrs fargs autoArgs // args;
# ...... 省略后面的内容 ...... # ...... 省略后面的内容 ......
``` ```
@ -97,7 +96,7 @@ nix-repl> import ./hello.nix pkgs
简单的说,它的使用格式是 `pkgs.callPackage fn args`,其中 `fn` 是一个 nix 文件或者函数,`args` 是一个 attribute set它的工作流程是 简单的说,它的使用格式是 `pkgs.callPackage fn args`,其中 `fn` 是一个 nix 文件或者函数,`args` 是一个 attribute set它的工作流程是
1. `pkgs.callPackage fn args` 会先判断 `fn` 是一个函数还是一个文件,如果是文件就先通过 `import xxx.nix` 导入其中定义的函数。 1. `pkgs.callPackage fn args` 会先判断 `fn` 是一个函数还是一个文件,如果是文件就先通过 `import xxx.nix` 导入其中定义的函数。
1. 第一步执行完毕得到的是一个函数,其参数通常会有 `lib`, `stdenv`, `fetchurl` 等参数,可能还会带有一些自定义参数。 1. 第一步执行完毕得到的是一个函数,其参数通常会有 `lib`, `stdenv`, `fetchurl` 等参数,可能还会带有一些自定义参数。
2. 之后,`pkgs.callPackage fn args` 会将 `args``pkgs` 这个 attribute set 合并。如果存在冲突,`args` 中的参数会覆盖 `pkgs` 中的参数。 2. 之后,`pkgs.callPackage fn args` 会将 `args``pkgs` 这个 attribute set 合并。如果存在冲突,`args` 中的参数会覆盖 `pkgs` 中的参数。
3. 再之后,`pkgs.callPackage fn args` 会从上一步得到的 attribute set 中提取出 `fn` 函数的参数,并使用它们来执行 `fn` 函数。 3. 再之后,`pkgs.callPackage fn args` 会从上一步得到的 attribute set 中提取出 `fn` 函数的参数,并使用它们来执行 `fn` 函数。
4. 函数执行结果是一个 Derivation也就是一个 Nix 包。 4. 函数执行结果是一个 Derivation也就是一个 Nix 包。

View File

@ -5,12 +5,11 @@
1. 通过实例化 commit id 不同的 nixpkgs 实例,用于安装不同版本的软件包。前面的 [降级与升级软件包](../nixos-with-flakes/downgrade-or-upgrade-packages.md) 一节中就是这样使用的。 1. 通过实例化 commit id 不同的 nixpkgs 实例,用于安装不同版本的软件包。前面的 [降级与升级软件包](../nixos-with-flakes/downgrade-or-upgrade-packages.md) 一节中就是这样使用的。
2. 如果希望使用 overlays但是又不想影响到默认的 nixpkgs 实例,可以通过实例化一个新的 nixpkgs 实例,然后在这个实例上使用 overlays。 2. 如果希望使用 overlays但是又不想影响到默认的 nixpkgs 实例,可以通过实例化一个新的 nixpkgs 实例,然后在这个实例上使用 overlays。
- 上一节 Overlays 中提到的 `nixpkgs.overlays = [...];` 是直接修改全局的 nixpkgs 实例,如果你的 overlays 改了比较底层的包,可能会影响到其他模块。坏处之一是会导致大量的本地编译(因为二进制缓存失效了),二是被影响的包功能可能也会出问题。 - 上一节 Overlays 中提到的 `nixpkgs.overlays = [...];` 是直接修改全局的 nixpkgs 实例,如果你的 overlays 改了比较底层的包,可能会影响到其他模块。坏处之一是会导致大量的本地编译(因为二进制缓存失效了),二是被影响的包功能可能也会出问题。
3. 在跨系统架构的编译中,你可以通过实例化多个 nixpkgs 实例来在不同的地方分别选用 QEMU 模拟编译与交叉编译,或者添加不同的 gcc 编译参数。 3. 在跨系统架构的编译中,你可以通过实例化多个 nixpkgs 实例来在不同的地方分别选用 QEMU 模拟编译与交叉编译,或者添加不同的 gcc 编译参数。
总之,实例化多个 nixpkgs 实例是非常有用的。 总之,实例化多个 nixpkgs 实例是非常有用的。
## `nixpkgs` 的实例化 ## `nixpkgs` 的实例化
先看看如何实例化一个非全局的 nixpkgs 实例,最常见的语法是: 先看看如何实例化一个非全局的 nixpkgs 实例,最常见的语法是:
@ -109,7 +108,7 @@ assert args ? system -> !(args ? localSystem);
import ./. (builtins.removeAttrs args [ "system" ] // { import ./. (builtins.removeAttrs args [ "system" ] // {
inherit config overlays localSystem; inherit config overlays localSystem;
}) })
`````` ```
因此 `import nixpkgs {...}` 实际就是调用了上面这个函数,后面的 attribute set 就是这个参数的参数。 因此 `import nixpkgs {...}` 实际就是调用了上面这个函数,后面的 attribute set 就是这个参数的参数。
@ -119,6 +118,3 @@ import ./. (builtins.removeAttrs args [ "system" ] // {
1. 根据 @fbewivpjsbsby 补充的文章 [1000 instances of nixpkgs](https://discourse.nixos.org/t/1000-instances-of-nixpkgs/17347),在子模块或者子 flakes 中用 `import` 来定制 `nixpkgs` 不是一个好的习惯,因为每次 `import` 都会重新求值并产生一个新的 nixpkgs 实例,在配置越来越多时会导致构建时间变长、内存占用变大。所以这里改为了在 `flake.nix` 中创建所有 nixpkgs 实例。 1. 根据 @fbewivpjsbsby 补充的文章 [1000 instances of nixpkgs](https://discourse.nixos.org/t/1000-instances-of-nixpkgs/17347),在子模块或者子 flakes 中用 `import` 来定制 `nixpkgs` 不是一个好的习惯,因为每次 `import` 都会重新求值并产生一个新的 nixpkgs 实例,在配置越来越多时会导致构建时间变长、内存占用变大。所以这里改为了在 `flake.nix` 中创建所有 nixpkgs 实例。
2. 在混合使用 QEMU 模拟编译与交叉编译时,搞得不好可能会导致许多包被重复编译多次,要注意避免这种情况。 2. 在混合使用 QEMU 模拟编译与交叉编译时,搞得不好可能会导致许多包被重复编译多次,要注意避免这种情况。

View File

@ -83,7 +83,7 @@
system = "x86_64-linux"; system = "x86_64-linux";
modules = [ modules = [
./configuration.nix ./configuration.nix
# 引入定义了 overlays 的 Module # 引入定义了 overlays 的 Module
(import ./overlays) (import ./overlays)
]; ];
@ -102,7 +102,6 @@
如果你只是想在某个地方使用 overlays而不想影响到全局的 nixpkgs 实例,可以通过实例化多个 nixpkgs 实例来实现。 如果你只是想在某个地方使用 overlays而不想影响到全局的 nixpkgs 实例,可以通过实例化多个 nixpkgs 实例来实现。
下一节 [多 nixpkgs 实例的妙用](./multiple-nixpkgs.md) 将会介绍如何做到这一点。 下一节 [多 nixpkgs 实例的妙用](./multiple-nixpkgs.md) 将会介绍如何做到这一点。
## 参考 ## 参考
- [Chapter 3. Overlays - nixpkgs Manual](https://nixos.org/manual/nixpkgs/stable/#chap-overlays) - [Chapter 3. Overlays - nixpkgs Manual](https://nixos.org/manual/nixpkgs/stable/#chap-overlays)

View File

@ -1,4 +1,3 @@
# Nix Flakes 的其他玩法 {#nix-flakes-usage} # Nix Flakes 的其他玩法 {#nix-flakes-usage}
到这里我们已经写了不少 Nix Flakes 配置来管理 NixOS 系统了,这里再简单介绍下 Nix Flakes 更细节的内容,以及常用的 nix flake 命令。 到这里我们已经写了不少 Nix Flakes 配置来管理 NixOS 系统了,这里再简单介绍下 Nix Flakes 更细节的内容,以及常用的 nix flake 命令。

View File

@ -1,9 +1,7 @@
# Testing # Testing
TODO TODO
## References ## References
- [Integration testing with NixOS virtual machines - nix.dev](https://nix.dev/tutorials/nixos/integration-testing-using-virtual-machines.html) - [Integration testing with NixOS virtual machines - nix.dev](https://nix.dev/tutorials/nixos/integration-testing-using-virtual-machines.html)

View File

@ -74,7 +74,6 @@ echo "Hello Nix" | nix run "nixpkgs#ponysay"
echo "Hello Nix" | nix run "github:NixOS/nixpkgs/nixos-unstable#ponysay" echo "Hello Nix" | nix run "github:NixOS/nixpkgs/nixos-unstable#ponysay"
``` ```
## `nix run``nix shell` 的常见用途 ## `nix run``nix shell` 的常见用途
那显然就是用来跑些临时命令,比如说我在新 NixOS 主机上恢复环境,但是还没有装 Git我可以直接用如下命令临时使用 Git 克隆我的配置仓库: 那显然就是用来跑些临时命令,比如说我在新 NixOS 主机上恢复环境,但是还没有装 Git我可以直接用如下命令临时使用 Git 克隆我的配置仓库:
@ -86,7 +85,7 @@ nix run nixpkgs#git clone git@github.com:ryan4yin/nix-config.git
或者也可以这样: 或者也可以这样:
```bash ```bash
nix shell nixpkgs#git nix shell nixpkgs#git
git clone git@github.com:ryan4yin/nix-config.git git clone git@github.com:ryan4yin/nix-config.git
``` ```

View File

@ -64,7 +64,6 @@ Nixpkgs 源码等各种资料中提取出我需要的信息,同时还要忽略
我希望这本书能帮助更多的人,让他们能够体验到 NixOS 的乐趣。希望你们喜欢它! 我希望这本书能帮助更多的人,让他们能够体验到 NixOS 的乐趣。希望你们喜欢它!
## 本书的特点 ## 本书的特点
1. 以 NixOS 与 Flakes 为核心进行讲解,摈弃了传统的 Nix 配置方式 1. 以 NixOS 与 Flakes 为核心进行讲解,摈弃了传统的 Nix 配置方式
@ -88,9 +87,6 @@ Nixpkgs 源码等各种资料中提取出我需要的信息,同时还要忽略
- [[2023-06-24] NixOS 与 Flakes | 一份非官方的新手指南 - v2ex 社区](https://www.v2ex.com/t/951190#reply9) - [[2023-06-24] NixOS 与 Flakes | 一份非官方的新手指南 - v2ex 社区](https://www.v2ex.com/t/951190#reply9)
- [[2023-06-24] NixOS 与 Flakes | 一份非官方的新手指南 - 0xffff 社区](https://0xffff.one/d/1547-nixos-yu-flakes-yi-fen-fei-guan) - [[2023-06-24] NixOS 与 Flakes | 一份非官方的新手指南 - 0xffff 社区](https://0xffff.one/d/1547-nixos-yu-flakes-yi-fen-fei-guan)
[^1]: [NixOS 与 Nix Flakes 新手入门](https://thiscute.world/posts/nixos-and-flake-basics/) [^1]: [NixOS 与 Nix Flakes 新手入门](https://thiscute.world/posts/nixos-and-flake-basics/)
[^2]: [NixOS & Nix Flakes - A Guide for Beginners - Reddit](https://www.reddit.com/r/NixOS/comments/13dxw9d/nixos_nix_flakes_a_guide_for_beginners/) [^2]: [NixOS & Nix Flakes - A Guide for Beginners - Reddit](https://www.reddit.com/r/NixOS/comments/13dxw9d/nixos_nix_flakes_a_guide_for_beginners/)
[^3]: [Updates: NixOS & Nix Flakes - A Guide for Beginners - Reddit](https://www.reddit.com/r/NixOS/comments/14fvz1q/comment/jp4xhj3/?context=3) [^3]: [Updates: NixOS & Nix Flakes - A Guide for Beginners - Reddit](https://www.reddit.com/r/NixOS/comments/14fvz1q/comment/jp4xhj3/?context=3)