OFFSET偏移
← 文章目录OFFSET / FIELD NOTESNO. 038

Home Manager 用户级配置管理教程

完整介绍安装、程序模块、dotfiles、服务和激活流程。

所在专题Home Manager:用户配置管理 ↗
约 22 分钟阅读开始阅读

示例版本与使用边界#

本教程保留 Home Manager/NixOS 24.05 的历史例子。它们用于说明模块结构,实际使用前需选择匹配且受支持的输入,并检查对应选项。home.stateVersion 是兼容行为基线,通常保留初次配置的值,不随输入升级。构建、激活和应用运行验证是不同层次。

管理范围#

Home Manager 是 Nix 生态系统中专门管理用户级配置的工具。它可以管理:

  • 用户软件包
  • 配置文件(dotfiles)
  • 环境变量
  • 服务(如 systemd 用户服务)

安装 Home Manager#

方式一:作为 NixOS 模块安装(推荐)

将 Home Manager 集成到 NixOS 系统配置中:

# /etc/nixos/configuration.nix
{ config, pkgs, ... }:

{
  imports = [
    # 导入 Home Manager NixOS 模块
    <home-manager/nixos>
  ];

  # 配置用户及 Home Manager
  users.users.alice = {
    isNormalUser = true;
    home = "/home/alice";
    description = "Alice";
  };

  # 为用户 alice 配置 Home Manager
  home-manager.users.alice = { pkgs, ... }: {
    home.packages = with pkgs; [
      git
      vim
      htop
    ];
    
    # Git 配置
    programs.git = {
      enable = true;
      userName = "Alice";
      userEmail = "alice@example.com";
    };
    
    # Bash 配置
    programs.bash = {
      enable = true;
      shellAliases = {
        ll = "ls -la";
        ".." = "cd ..";
      };
    };
    
    # 状态版本(必须设置)
    home.stateVersion = "24.05";
  };
}

重建系统:

sudo nixos-rebuild switch

方式二:独立安装(非 NixOS 系统)

在任何 Linux/macOS 系统上安装:

# 添加 nix-channel 通道
nix-channel --add https://github.com/nix-community/home-manager/archive/release-24.05.tar.gz home-manager
nix-channel --update

# 安装
nix-shell '<home-manager>' -A install

创建配置文件:

# 生成初始配置
home-manager init

# 编辑
nano ~/.config/home-manager/home.nix

方式三:使用 Flakes 安装(现代方式)

# ~/.config/home-manager/flake.nix
{
  description = "Home Manager configuration";

  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.05";
    home-manager = {
      url = "github:nix-community/home-manager/release-24.05";
      inputs.nixpkgs.follows = "nixpkgs";
    };
  };

  outputs = { self, nixpkgs, home-manager }: {
    homeConfigurations."alice" = home-manager.lib.homeManagerConfiguration {
      pkgs = nixpkgs.legacyPackages.x86_64-linux;
      modules = [ ./home.nix ];
    };
  };
}
# ~/.config/home-manager/home.nix
{ config, pkgs, ... }:

{
  home.username = "alice";
  home.homeDirectory = "/home/alice";

  home.packages = with pkgs; [
    firefox
    thunderbird
  ];

  home.stateVersion = "24.05";
  programs.home-manager.enable = true;
}

激活配置:

home-manager switch --flake ~/.config/home-manager#alice

Home Manager 基础配置#

基本结构

{ config, pkgs, ... }:

{
  # 用户基本信息
  home.username = "alice";
  home.homeDirectory = "/home/alice";
  home.stateVersion = "24.05";  # 必需

  # 用户级别的软件包
  home.packages = with pkgs; [
    # 开发工具
    git
    vim
    tmux
    
    # 日常软件
    firefox
    vlc
    
    # 命令行工具
    htop
    ripgrep
    fd
    fzf
    bat
  ];

  # 启用 Home Manager
  programs.home-manager.enable = true;
}

常用命令详解

# 激活配置
home-manager switch

# 激活特定配置(Flakes)
home-manager switch --flake ~/my-config#user

# 构建配置,不激活,也不是运行时测试
home-manager build

# 回滚到上一版本
home-manager switch --rollback

# 查看历史版本
home-manager generations

# 激活指定历史代际(先从 generations 输出确认实际路径)
/path/from/home-manager-generations/activate

# 编辑配置文件
home-manager edit

# 检查构建出的激活脚本(不执行)
home-manager build
less result/activate

# 清理旧版本
home-manager expire-generations "-30 days"

程序配置#

Git 完整配置

programs.git = {
  enable = true;
  userName = "Alice";
  userEmail = "alice@example.com";
  
  # 额外配置
  extraConfig = {
    init.defaultBranch = "main";
    push.autoSetupRemote = true;
    pull.ff = "only";
    core = {
      editor = "vim";
      autocrlf = "input";
    };
  };
  
  # 忽略文件
  ignores = [
    "*.swp"
    "*.swo"
    ".DS_Store"
    "node_modules/"
  ];
  
  # Aliases
  aliases = {
    st = "status";
    co = "checkout";
    br = "branch";
    ci = "commit";
    lg = "log --oneline --graph --all";
  };
};

Vim/Neovim 配置

programs.vim = {
  enable = true;
  
  settings = {
    number = true;        # 显示行号
    relativenumber = true; # 相对行号
    tabstop = 2;          # Tab 宽度
    shiftwidth = 2;       # 缩进宽度
    expandtab = true;     # 空格代替 tab
    mouse = "a";          # 启用鼠标
  };
  
  extraConfig = ''
    " 自定义配置
    set hlsearch
    set incsearch
    set smartcase
    set ignorecase
    set clipboard=unnamedplus
    
    " 配色
    syntax on
    colorscheme desert
  '';
  
  # 插件(需要额外配置)
  plugins = with pkgs.vimPlugins; [
    vim-airline
    nerdtree
  ];
};

# 或使用 Neovim
programs.neovim = {
  enable = true;
  defaultEditor = true;
  
  plugins = with pkgs.vimPlugins; [
  nvim-treesitter
  telescope-nvim
  ];
  
  extraConfig = ''
    lua << EOF
    -- Lua 配置
    vim.wo.number = true
    vim.bo.expandtab = true
    EOF
  '';
};

Bash/Zsh/Fish 配置

# Bash
programs.bash = {
  enable = true;
  
  # 环境变量
  sessionVariables = {
    EDITOR = "vim";
    PAGER = "less";
    PATH = "$HOME/.local/bin:$PATH";
  };
  
  # 别名
  shellAliases = {
    ll = "ls -la";
    la = "ls -a";
    ".." = "cd ..";
    "..." = "cd ../..";
  };
  
  # 初始化脚本
  initExtra = ''
    # 自定义函数
    mkcd() {
      mkdir -p "$@" && cd "$@"
    }
    
    # 提示符
    PS1='\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
  '';
};

# Zsh(推荐)
programs.zsh = {
  enable = true;
  
  oh-my-zsh = {
    enable = true;
    theme = "robbyrussell";
    plugins = [ "git" "docker" "sudo" ];
  };
  
  zplug = {
    enable = true;
    plugins = [
      { name = "zsh-users/zsh-autosuggestions"; }
      { name = "zsh-users/zsh-syntax-highlighting"; }
    ];
  };
  
  # 环境变量
  envExtra = ''
    export PATH="$HOME/.cargo/bin:$PATH"
  '';
  
  shellAliases = {
    g = "git";
    ga = "git add";
    gc = "git commit";
    gp = "git push";
  };
};

# Fish
programs.fish = {
  enable = true;
  
  plugins = [
    { name = "fisher"; src = pkgs.fishPlugins.fisher.src; }
  ];
  
  shellAliases = {
    l = "ls -la";
    c = "clear";
  };
  
  shellInit = ''
    # Fish 配置
    set -x EDITOR vim
  '';
};

SSH 配置

programs.ssh = {
  enable = true;
  
  # 主机配置
  matchBlocks = {
    "github" = {
      host = "github.com";
      user = "git";
      identityFile = "~/.ssh/id_ed25519";
    };
    
    "myserver" = {
      host = "server.example.com";
      user = "admin";
      port = 2222;
      identityFile = "~/.ssh/id_server";
      extraOptions = {
        "ServerAliveInterval" = "60";
        "ServerAliveCountMax" = "3";
      };
    };
  };
  
  # 全局配置
  extraConfig = ''
    AddKeysToAgent yes
    IgnoreUnknown UseKeychain
    UseKeychain yes # 主要针对 macOS;Linux 通常应删除这一项
  '';
};

Tmux 配置

programs.tmux = {
  enable = true;
  
  # 快捷键前缀
  shortcut = "a";  # Ctrl+a
  
  # 基础配置
  baseIndex = 1;
  escapeTime = 0;
  historyLimit = 10000;
  
  # 插件
  plugins = with pkgs.tmuxPlugins; [
    sensible
    yank
    resurrect
    continuum
  ];
  
  extraConfig = ''
    # 鼠标支持
    set -g mouse on
    
    # 状态栏
    set -g status-bg black
    set -g status-fg white
    
    # 窗口标题
    set -g set-titles on
    set -g set-titles-string "#W"
    
    # 重新加载配置
    bind r source-file ~/.config/tmux/tmux.conf \; display "配置已重载!"
    
    # 窗口分割
    bind | split-window -h
    bind - split-window -v
    
    # 同步窗格
    bind y setw synchronize-panes
  '';
};

文件管理(Dotfiles)#

Home Manager 可以直接管理任意配置文件:

# 创建配置文件
home.file = {
  # 简单的文本文件
  ".config/myapp/config.toml".text = ''
    [settings]
    theme = "dark"
    language = "zh"
  '';
  
  # 从本地文件复制
  ".config/alacritty/alacritty.yml".source = ./dotfiles/alacritty.yml;
  
  # 从 store 路径
  ".config/doom/config.el".source = pkgs.fetchFromGitHub {
    owner = "hlissner";
    repo = "doom-emacs";
    rev = "<fixed-commit>";
    hash = "sha256-<actual-source-hash>";
  } + "/templates/config.example.el";
  
  # 可执行脚本
  ".local/bin/my-script" = {
    source = ./scripts/my-script.sh;
    executable = true;
  };
  
  # 目录
  ".config/nvim/lua/custom".source = ./nvim-lua;
};

# 使用 xdg 配置(推荐)
xdg.configFile = {
  "i3/config".source = ./i3-config;
  "polybar/config.ini".text = ''
    [bar/main]
    width = 100%
    height = 30
  '';
};

xdg.dataFile = {
  # 数据文件
  "applications/myapp.desktop" = {
    text = ''
      [Desktop Entry]
      Name=MyApp
      Exec=myapp
      Type=Application
    '';
  };
};

服务管理#

services = {
  # GPG 代理
  gpg-agent = {
    enable = true;
    enableSshSupport = true;
    pinentryPackage = pkgs.pinentry-curses;
  };
  
  # 密码管理器
  password-store = {
    enable = true;
    settings = {
      PASSWORD_STORE_DIR = "~/.password-store";
    };
  };
  
  # 剪贴板管理
  copyq = {
    enable = true;
  };
  
  # 键位修改
  keynav = {
    enable = true;
  };
};

完整示例#

{ config, pkgs, lib, ... }:

{
  home.username = "alice";
  home.homeDirectory = "/home/alice";
  home.stateVersion = "24.05";

  # === 软件包 ===
  home.packages = with pkgs; [
    # 开发
    git
    vim
    tmux
    vscode
    jetbrains.idea-community
    
    # 工具
    htop
    ripgrep
    fd
    fzf
    bat
    eza
    
    # 浏览器
    firefox
    chromium
    
    # 通讯
    thunderbird
    slack
    
    # 多媒体
    vlc
    obs-studio
  ];

  # === 程序配置 ===
  programs.home-manager.enable = true;
  
  programs.git = {
    enable = true;
    userName = "Alice";
    userEmail = "alice@example.com";
    extraConfig = {
      init.defaultBranch = "main";
      core.editor = "vim";
    };
  };
  
  programs.zsh = {
    enable = true;
    oh-my-zsh = {
      enable = true;
      theme = "robbyrussell";
      plugins = [ "git" "docker" ];  
    };
    shellAliases = {
      g = "git";
      l = "ls -la";
    };
  };
  
  programs.tmux = {
    enable = true;
    plugins = with pkgs.tmuxPlugins; [
      sensible yank
    ];
  };
  
  # === 环境变量 ===
  home.sessionVariables = {
    EDITOR = "vim";
    BROWSER = "firefox";
    TERMINAL = "alacritty";
  };
  
  # === 配置文件 ===
  home.file = {
    ".myconfig".text = "配置内容";
  };
  
  # === 服务 ===
  services.gpg-agent = {
    enable = true;
    enableSshSupport = true;
  };
}

Home Manager 的工作原理#

┌─────────────────────────────────────────┐
│         home.nix (你的配置)              │
└─────────────────┬───────────────────────┘
                  │ 解析为 Nix 表达式
                  ▼
┌─────────────────────────────────────────┐
│      Home Manager 生成激活脚本          │
│    - 创建符号链接到 ~/.config/           │
│    - 安装软件包到 ~/.nix-profile/        │
│    - 设置环境变量                        │
│    - 启动用户服务                        │
└─────────────────────────────────────────┘

激活时,Home Manager 会:

  1. 创建所有配置文件(符号链接)
  2. 安装指定的软件包
  3. 设置环境变量和别名
  4. 启动/停止相应服务
  5. 维护 Home Manager 代际;已有普通文件冲突通常会阻止激活,备份需要显式配置(例如 CLI 的 -b backup)。

当前版本的接口检查#

历史例子使用 Git 的 userName、userEmail 和 extraConfig;当前 Home Manager 已提供向 programs.git.settings 迁移的兼容入口。Shell、编辑器和桌面选项也应以锁定版本为准。Home Manager 代际恢复的是其管理的配置和包,不会恢复应用数据库、秘密或其他可变数据。

参考与延伸

  1. Home Manager 手册 ↗
  2. Home Manager 命令源码 ↗
  3. Home Manager 文件选项源码 ↗
  4. Home Manager Git 模块源码 ↗

根据技术笔记重新整理,示例使用通用名称。

沿专题继续阅读

Home Manager:用户配置管理

  1. 01Home Manager 集成与模块化
  2. 02Home Manager 终端环境配置
  3. 03Home Manager 桌面与主题配置
  4. 04Home Manager 文件与符号链接
  5. 05Home Manager 与 NixOS 密钥管理
  6. 06Home Manager 用户级配置管理教程
CONTINUE READING / 下一篇文件与目录操作

从目录浏览、文件查找到链接、归档和空间查询,掌握日常文件操作。