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
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
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
title: ""
labels: ""
assignees: ""
---
**Describe the bug**
@ -12,6 +11,7 @@ A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
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.
**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**
Add any other context about the problem here.

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,22 +1,22 @@
// .vitepress/theme/index.ts
import DefaultTheme from "vitepress/theme";
import giscusTalk from "vitepress-plugin-comment-with-giscus";
import { useData, useRoute } from "vitepress";
import DefaultTheme from "vitepress/theme"
import giscusTalk from "vitepress-plugin-comment-with-giscus"
import { useData, useRoute } from "vitepress"
// custom CSS
import "../style/print.css";
import "../style/print.css"
export default {
// Extending the Default Theme
...DefaultTheme,
enhanceApp(ctx) {
DefaultTheme.enhanceApp(ctx);
DefaultTheme.enhanceApp(ctx)
// ...
},
setup() {
// Get frontmatter and route
const { frontmatter } = useData();
const route = useRoute();
const { frontmatter } = useData()
const route = useRoute()
// Obtain configuration from: https://giscus.app/
giscusTalk(
@ -41,7 +41,7 @@ export default {
// The default is true, which means enabled, this parameter can be ignored;
// If it is false, it means it is not enabled.
// 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 config from './config'
import { defineUserConfig } from "vitepress-export-pdf"
import config from "./config"
// convert `config.themeConfig?.sidebar` to a list of routes
let routeOrder = [];
const sidebar = config.locales.root.themeConfig?.sidebar;
let routeOrder = []
const sidebar = config.locales.root.themeConfig?.sidebar
if (sidebar) {
sidebar.forEach((it) => {
if (it.items) {
it.items.forEach((subItem) => {
routeOrder.push(subItem.link.replace(/\.md$/, ""));
});
routeOrder.push(subItem.link.replace(/\.md$/, ""))
})
}
});
})
}
// print routeOrder in terminal
console.log("routeOrder: ", routeOrder);
console.log("routeOrder: ", routeOrder)
export default defineUserConfig({
routePatterns: ["!/zh/**"], // exclude zh-CN pages
sorter: (pageA, pageB) => {
const aIndex = routeOrder.findIndex(route => route === pageA.path);
const bIndex = routeOrder.findIndex(route => route === pageB.path);
const index = aIndex - bIndex;
// console.log(`sorter: ${pageA.path} vs ${pageB.path} = ${index}`);
return index;
},
urlOrigin: "https://nixos-and-flakes.thiscute.world/",
});
routePatterns: ["!/zh/**"], // exclude zh-CN pages
sorter: (pageA, pageB) => {
const aIndex = routeOrder.findIndex((route) => route === pageA.path)
const bIndex = routeOrder.findIndex((route) => route === pageB.path)
const index = aIndex - bIndex
// console.log(`sorter: ${pageA.path} vs ${pageB.path} = ${index}`);
return index
},
urlOrigin: "https://nixos-and-flakes.thiscute.world/",
})

View File

@ -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 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
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.
## Debugging functions provided by nixpkgs
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/)
- 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)

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:
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.
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. 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..
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.
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.
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.
1. If you encounter any issues, resolve them before proceeding.
1. Use the `users.users.<name>.openssh.authorizedKeys.keys` option to complete this task.
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.
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.
It's advisable to use the `root` user for deployment as it's more convenient and avoids the complexities of sudo permissions.

View File

@ -77,7 +77,6 @@ idols: aqua ruby kana
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.
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

@ -13,7 +13,6 @@ which encapsulates Nix more thoroughly and provides users with a simpler definit
- [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,
here's a tool that might meet your needs:
@ -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:
> 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,
and these modification commands can only be executed during the Nix build phase.
> 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.
- [DavHau/mach-nix](https://github.com/DavHau/mach-nix) (currently unmaintained)
- [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.
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.
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

@ -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.
## 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`.
Here is an example:
```nix
{
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.
## Creating a Development Environment with `pkgs.runCommand`
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/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
Now let's take a look at `nix develop`, first read the help document output by `nix develop --help`:
@ -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)
[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.
## 参考文档
- [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
- [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`

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.
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. 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.
## What are the advantages of Nix compared to Docker container technology?
@ -80,34 +80,33 @@ 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`.
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
{
# as a nixos module
# environment.systemPackages = with pkgs; [
#
# or as a home manager module
home.packages = let
custom-python3 = (pkgs.python311.withPackages (ps:
with ps; [
ipython
pandas
requests
pyquery
pyyaml
]
));
in
with pkgs; [
# override the version of python3
# NOTE: This will trigger a rebuild of lldb, it takes time
(lldb.override {
python3 = custom-python3;
})
custom-python3
];
}
```
```nix
{
# as a nixos module
# environment.systemPackages = with pkgs; [
#
# or as a home manager module
home.packages = let
custom-python3 = (pkgs.python311.withPackages (ps:
with ps; [
ipython
pandas
requests
pyquery
pyyaml
]
));
in
with pkgs; [
# override the version of python3
# NOTE: This will trigger a rebuild of lldb, it takes time
(lldb.override {
python3 = custom-python3;
})
custom-python3
];
}
```

View File

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

View File

@ -43,4 +43,3 @@ The development environment of three desktop computers is managed by Home Manage
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!

View File

@ -229,7 +229,7 @@ In other words, you can use it like this:
## 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)
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.
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.
@ -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.
> 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

@ -290,7 +290,6 @@ echo 'insert after default';"
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).
## References

View File

@ -37,7 +37,6 @@ After making these changes, run `sudo nixos-rebuild switch` to apply the modific
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.
## 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`.
@ -101,7 +100,6 @@ Up to this point, `/etc/nixos/flake.nix` has merely been a thin wrapper around `
>
> 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}
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.
@ -131,7 +129,6 @@ Here we only define a dependency named `nixpkgs`, which is the most common way t
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
Now let's look at `outputs`.
@ -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.
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.
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.
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.
@ -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 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}
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).
## 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.
@ -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.
- [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/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

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
```
## Why some packages are installed?
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. `w` to show the package is depended by which packages, and the full dependency chain.
## Reducing 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. 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?
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
```
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
sudo kubectl
kubectl controls the Kubernetes cluster manager.
...
```

View File

@ -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):
```nix
/* Call the package function in the file `fn` with the required
arguments automatically. The function is called with the
@ -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)
- [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)

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).
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.
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.
2. When mixing QEMU simulation and cross-compilation, care should be taken to avoid unnecessary duplication of package compilations.

View File

@ -92,7 +92,6 @@ 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.
## 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.

View File

@ -55,4 +55,3 @@ The `inputs` section in `flake.nix` is an attribute set used to specify the depe
outputs = { self, ... }@inputs: { ... };
}
```

View File

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

View File

@ -87,4 +87,3 @@ git clone git@github.com:ryan4yin/nix-config.git
```
[New Nix Commands]: https://nixos.org/manual/nix/stable/command-ref/new-cli/nix.html

View File

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

View File

@ -9,10 +9,9 @@ To get started, I recommend reading the following resources for a quick introduc
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.
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.
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.
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}
## 社区
- [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 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 包管理器的演讲也很值得一阅:
- [金枪鱼之夜Nix - 从构建系统到配置管理](https://www.bilibili.com/video/BV13Y411p7DS/)
@ -60,5 +58,3 @@
- ...
想了解更多内容,可以看看 [awesome-nix](https://github.com/nix-community/awesome-nix).

View File

@ -27,4 +27,3 @@ nvim-test: nvim-clean
测试完毕后,运行下 `just nvim-clean`,再重新用 `nixos-rebuild` 部署下配置,就完成了配置的还原。
这种方法能生效的前提是,你的 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 配置后,就能很方便地检查所有的配置项了,这对于调试非常有用。
## 使用 nixpkgs 中提供的调试函数
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/)
- 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)

View File

@ -18,7 +18,6 @@ Flake Registry 是一个 Flake 注册中心,它可以帮助我们在使用 `ni
比如说我们执行 `nix run nixpkgs#ponysay hello`nix 会自动从上述 json 文件中找到 `nixpkgs` 对应的 github 仓库地址,然后下载这个仓库,再通过其中的 `flake.nix` 查找对应的 `ponysay` 包并运行它。
## 自定义 NIX_PATH 与 Flake Registry {#custom-nix-path-and-flake-registry-2}
> **注意:新手请先跳过这部分内容!因为配置如果抄得不对,关掉 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)

View File

@ -14,15 +14,15 @@ Nix 本身的设计就很适合远程部署Nix 社区也有许多专门用于
在进行远程部署之前,需要做一些准备工作:
1. 为了防止远程主机的 sudo 密码验证失败,有两种方法,二选一:
1. 以远程主机的 `root` 用户身份部署,这是推荐使用的方法。
2. 在远程主机的配置中添加 `security.sudo.wheelNeedsPassword = false;` 并提前手动部署一次,从而为用户授予免密码验证的 sudo 权限。
1. **这会导致用户级别的程序能静默获取 sudo 权限,存在安全风险**!因此如果选用这种方法,建议远程部署创建一个专门的用户,不应该使用自己的常用用户!
1. 以远程主机的 `root` 用户身份部署,这是推荐使用的方法。
2. 在远程主机的配置中添加 `security.sudo.wheelNeedsPassword = false;` 并提前手动部署一次,从而为用户授予免密码验证的 sudo 权限。
1. **这会导致用户级别的程序能静默获取 sudo 权限,存在安全风险**!因此如果选用这种方法,建议远程部署创建一个专门的用户,不应该使用自己的常用用户!
2. 为远程主机配置 SSH 公钥身份验证
1. 可使用 `users.users.<name>.openssh.authorizedKeys.keys` 配置项完成配置。
1. 在本机主机上添加好远程主机的 Known Hosts 记录,否则 colmena/nixos-rebuild 会因为无法验证远程主机的身份而部署失败。
1. 可使用 `programs.ssh.knownHosts` 配置项将远程主机的公钥添加到 Known Hosts 记录中。
1. 手动使用 `ssh root@<you-host>` 命令,验证能正常登录到远程主机。
1. 如果遇到任何问题,请先解决它们,再继续后续操作。
1. 可使用 `users.users.<name>.openssh.authorizedKeys.keys` 配置项完成配置。
3. 在本机主机上添加好远程主机的 Known Hosts 记录,否则 colmena/nixos-rebuild 会因为无法验证远程主机的身份而部署失败。
1. 可使用 `programs.ssh.knownHosts` 配置项将远程主机的公钥添加到 Known Hosts 记录中。
4. 手动使用 `ssh root@<you-host>` 命令,验证能正常登录到远程主机。
1. 如果遇到任何问题,请先解决它们,再继续后续操作。
建议使用 `root` 用户进行部署,因为这更方便且不需要额外的配置,没有令人头疼的 sudo 权限问题。
@ -140,4 +140,3 @@ Host aquamarine
```bash
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 封装工具帮我们干这个活:
> 注意即使是在这俩环境中,直接跑 `pip install` 之类的安装命令仍然是会失败的,必须通过 `flake.nix` 来安装 Python 依赖!
因为数据还是在 `/nix/store` 中,这类修改命令必须在 Nix 的构建阶段才能执行...
> 因为数据还是在 `/nix/store` 中,这类修改命令必须在 Nix 的构建阶段才能执行...
- [DavHau/mach-nix](https://github.com/DavHau/mach-nix)
- [poetry2nix](https://github.com/nix-community/poetry2nix)
这俩工具的好处是,能利用上 Nix Flakes 的锁机制来提升可复现能力,缺点是多了一层封装,底层变得更复杂了。
最后,在一些更复杂的项目上,上述两种方案可能都行不通,这时候最佳的解决方案,就是改用容器了,比如 Docker、Podman 等,容器的限制没 Nix 这么严格,能提供最佳的兼容性。

View File

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

View File

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

View File

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

View File

@ -38,13 +38,11 @@ NixOS 的回滚能力与可复现能力给了我非常大的底气,我现在
目前我的个人配置 [ryan4yin/nix-config](https://github.com/ryan4yin/nix-config) 同步管理了许多主机的配置:
- 桌面电脑
- 一台 Macbook Pro 2020 (Intel amd64)
- 一台 Macbook Pro 2022 (M2 aarch64)
- 一台 NixOS 桌面 PC (amd64)
- 一台 Macbook Pro 2020 (Intel amd64)
- 一台 Macbook Pro 2022 (M2 aarch64)
- 一台 NixOS 桌面 PC (amd64)
- 服务器
- 三台 NixOS 虚拟机(amd64)
- 若干块 aarch64 跟 riscv64 的开发板
- 三台 NixOS 虚拟机(amd64)
- 若干块 aarch64 跟 riscv64 的开发板
其中三台桌面电脑的开发环境都通过 Home Manager 管理,主要配置完全共用,在任意一台主机上修改的配置,可以通过 Git 无缝同步到其他主机上。NixOS 几乎完全帮我屏蔽了三台机器底层的 OS 与芯片架构差异,体验非常丝滑!

View File

@ -14,7 +14,6 @@ NixOS 的安装步骤很简单,这里不多介绍,仅列一下我觉得比
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.
## 对中国大陆用户流畅使用 NixOS 的建议
国内用户在使用 NixOS 时会存在一些网络问题,一是 NixOS 高度依赖 GitHub 作为 channel/flake 数据源——在国内访问 GitHub 相当的慢,二是 NixOS 官方的包缓存服务器在国内访问速度较慢。
@ -23,7 +22,6 @@ NixOS 的安装步骤很简单,这里不多介绍,仅列一下我觉得比
这里我先介绍几个比较简单的配置方法。
### 1. 包缓存服务器的加速访问
首先,在执行后面给出的任何 `nix` 相关命令时,你都可以通过 `--option` 选项来指定镜像源,例如:
@ -47,7 +45,6 @@ nix shell nixpkgs#cowsay --option substituters "https://mirrors.tuna.tsinghua.ed
你可以自己测试下上述几个镜像源的速度,选速度最快的一个。
### 2. Channel/Flake 的加速访问
对于 Flake Inputs 跟 Channels 的加速访问,这个就需要使用代理工具加速访问。

View File

@ -270,6 +270,5 @@ sudo systemctl restart 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)
> 可尝试通过更换代理服务器或者设置 [access-tokens](https://github.com/NixOS/nix/issues/6536) 来解决。

View File

@ -49,7 +49,6 @@ Flakes 带来的好处是显而易见的,整个 NixOS 社区都很喜欢它,
读完上述内容后,个人猜测,**Flakes 有可能(仅是可能)会在未来两年内成为稳定特性**。
## 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 社区广泛使用。
@ -74,7 +73,6 @@ Nix 于 2020 年推出了 `nix-command` & `flakes` 两个实验特性,它们
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]: [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/)
[^3]: [Draft: 1 year roadmap - NixOS Foundation](https://nixos-foundation.notion.site/1-year-roadmap-0dc5c2ec265a477ea65c549cd5e568a9)

View File

@ -269,7 +269,6 @@ echo 'insert after default';"
可以看到,`lib.mkBefore` 会将后面的值插入到前面,而 `lib.mkAfter` 会将后面的值插入到前面。
> 对模块系统更深入的介绍,参见 [模块系统与自定义 options](../other-usage-of-flakes/module-system.md).
## References

View File

@ -218,7 +218,6 @@ sudo nixos-rebuild switch --flake github:owner/repo#your-hostname
新手阶段了解这些就足够了,探究 `nixpkgs.lib.nixosSystem` 函数的具体实现需要对 Nixpkgs 的模块系统有一定的了解。
读者可以在学习了 [模块化 NixOS 配置](./modularize-the-configuration.md) 一节后,再回过头来从 [nixpkgs/flake.nix] 中找到 `nixpkgs.lib.nixosSystem` 的定义,跟踪它的源码,研究其实现方式。
## Nixpkgs Module 结构的简单介绍 {#simple-introduction-to-nixpkgs-module-structure}
> 在后面的 [模块化 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 提供的功能。
- [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/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

View File

@ -80,7 +80,6 @@ sudo nix-collect-garbage --delete-old
1. `/<package-name>` 以查找到你想查询的包
1. 输入 `w`,看看谁依赖了它(`why depends`),以及完整的依赖链。
## 节约存储空间
如下配置可以比较好的缩减 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 安装的软件与配置,可以更好地隔离不同用户的环境,避免不同用户之间的配置与软件版本冲突。
## 如何以特权身份使用 Home Manager 安装的软件包?
对这个问题,首先想到的一般都是直接切换到 `root` 用户, 可切换用户后,当前用户通过 `home.nix` 安装的软件包都将不可用。
@ -294,5 +293,3 @@ Error: nu::shell::external_command
kubectl controls the Kubernetes cluster manager.
...
```

View File

@ -27,7 +27,7 @@ nix-repl> pkgs.writeShellScriptBin "hello" '' echo "hello, xxx!" ''
前面我们介绍并大量使用了 `import xxx.nix` 来从其他 Nix 文件中导入 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` 作为参数来执行其中定义的函数。
仍然使用 `nix repl` 来验证一下,能看到它的执行结果仍然是一个 Derivation
@ -53,12 +53,11 @@ nix-repl> import ./hello.nix pkgs
在前面不使用 `pkgs.callPackage` 的例子中,我们直接将 `pkgs` 作为参数传到了 `hello.nix` 中,这样做的缺点有:
1. `hello` 这个 derivation 的所有其他依赖项都只能从 `pkgs` 中获取,耦合度太高。
1. 比如说我们如果需要其他自定义依赖项,就必须修改 `pkgs` 或者修改 `hello.nix` 的内容,而这两个都很麻烦。
1. 比如说我们如果需要其他自定义依赖项,就必须修改 `pkgs` 或者修改 `hello.nix` 的内容,而这两个都很麻烦。
1. 在 `hello.nix` 变复杂的情况下,很难判断 `hello.nix` 到底依赖了 `pkgs` 中的哪些 Derivation很难分析 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
/* Call the package function in the file `fn` with the required
@ -97,7 +96,7 @@ nix-repl> import ./hello.nix pkgs
简单的说,它的使用格式是 `pkgs.callPackage fn args`,其中 `fn` 是一个 nix 文件或者函数,`args` 是一个 attribute set它的工作流程是
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` 中的参数。
3. 再之后,`pkgs.callPackage fn args` 会从上一步得到的 attribute set 中提取出 `fn` 函数的参数,并使用它们来执行 `fn` 函数。
4. 函数执行结果是一个 Derivation也就是一个 Nix 包。

View File

@ -5,12 +5,11 @@
1. 通过实例化 commit id 不同的 nixpkgs 实例,用于安装不同版本的软件包。前面的 [降级与升级软件包](../nixos-with-flakes/downgrade-or-upgrade-packages.md) 一节中就是这样使用的。
2. 如果希望使用 overlays但是又不想影响到默认的 nixpkgs 实例,可以通过实例化一个新的 nixpkgs 实例,然后在这个实例上使用 overlays。
- 上一节 Overlays 中提到的 `nixpkgs.overlays = [...];` 是直接修改全局的 nixpkgs 实例,如果你的 overlays 改了比较底层的包,可能会影响到其他模块。坏处之一是会导致大量的本地编译(因为二进制缓存失效了),二是被影响的包功能可能也会出问题。
- 上一节 Overlays 中提到的 `nixpkgs.overlays = [...];` 是直接修改全局的 nixpkgs 实例,如果你的 overlays 改了比较底层的包,可能会影响到其他模块。坏处之一是会导致大量的本地编译(因为二进制缓存失效了),二是被影响的包功能可能也会出问题。
3. 在跨系统架构的编译中,你可以通过实例化多个 nixpkgs 实例来在不同的地方分别选用 QEMU 模拟编译与交叉编译,或者添加不同的 gcc 编译参数。
总之,实例化多个 nixpkgs 实例是非常有用的。
## `nixpkgs` 的实例化
先看看如何实例化一个非全局的 nixpkgs 实例,最常见的语法是:
@ -109,7 +108,7 @@ assert args ? system -> !(args ? localSystem);
import ./. (builtins.removeAttrs args [ "system" ] // {
inherit config overlays localSystem;
})
``````
```
因此 `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 实例。
2. 在混合使用 QEMU 模拟编译与交叉编译时,搞得不好可能会导致许多包被重复编译多次,要注意避免这种情况。

View File

@ -102,7 +102,6 @@
如果你只是想在某个地方使用 overlays而不想影响到全局的 nixpkgs 实例,可以通过实例化多个 nixpkgs 实例来实现。
下一节 [多 nixpkgs 实例的妙用](./multiple-nixpkgs.md) 将会介绍如何做到这一点。
## 参考
- [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 配置来管理 NixOS 系统了,这里再简单介绍下 Nix Flakes 更细节的内容,以及常用的 nix flake 命令。

View File

@ -1,9 +1,7 @@
# Testing
TODO
## References
- [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"
```
## `nix run``nix shell` 的常见用途
那显然就是用来跑些临时命令,比如说我在新 NixOS 主机上恢复环境,但是还没有装 Git我可以直接用如下命令临时使用 Git 克隆我的配置仓库:

View File

@ -64,7 +64,6 @@ Nixpkgs 源码等各种资料中提取出我需要的信息,同时还要忽略
我希望这本书能帮助更多的人,让他们能够体验到 NixOS 的乐趣。希望你们喜欢它!
## 本书的特点
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 | 一份非官方的新手指南 - 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/)
[^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)