用 Chezmoi 取回你的点文件
点文件
![](/data/attachment/album/202004/14/183618dwkhe4ehx1kthxvw.jpg)


在 Linux 中，点文件是隐藏的文本文件，从 Bash、Git 到 i3 或 VSCode 等更复杂的许多应用程序，都用它存储配置设置。


这些文件大多数都放在 `~/.config` 目录中或用户主目录中。编辑这些文件使你可以自定义也许没有提供设置菜单的应用程序，并且它们可以跨设备甚至是跨其它 Linux 发行版移植。但是，整个 Linux 发烧友社区的讨论焦点是如何管理这些点文件以及如何共享它们。


我们将展示一个名为 [Chezmoi](https://www.chezmoi.io/) 的工具，该工具与其它工具略有不同。


### 点文件管理的历史


如果你在 [GitHub 上搜索“dotfiles”](https://github.com/search?q=dotfiles&type=Repositories)，那么你将看到有超过 10 万个存储库在解决一个目标：将人们的点文件存储在可共享且可重复的领地中。但是，除了都在使用 Git 之外，它们存储文件的方式各有不同。


虽然 Git 解决了代码管理问题，也将其转换为配置文件管理，但它并没有解决如何区分发行版、角色（例如家用计算机与工作计算机）、机密信息管理以及按设备配置的问题。


因此，许多用户决定制定自己的解决方案，多年来，社区已经做出了许多成果。本文将简要介绍已有的一些解决方案。


#### 在孤立的环境中进行实验


你想在封闭的环境中快速尝试以下解决方案吗？运行：



```
$ podman run --rm -it fedora
```

来创建一个 Fedora 容器尝试应用程序。退出容器时，该容器将自动删除自身。


#### 安装问题


如果将点文件存储在 Git 存储库中，你肯定希望可以让更改轻松地自动应用到主目录之中，乍一看，最简单的方法是使用符号链接，例如 `ln -s ~/.dotfies/bashrc ~/.bashrc`。这可以使你的更改在更新存储库时立即就绪。


符号链接的问题在于管理符号链接可能很麻烦。Stow 和 [RCM](https://fedoramagazine.org/managing-dotfiles-rcm/)（在 Fedora 杂志上介绍过）可以帮助你管理这些，但是这些并不是非常舒服的解决方案。下载后，需要对私有文件进行适当的修改和设置访问模式。如果你在一个系统上修改了点文件，然后将存储库下载到另一个系统，则可能会发生冲突并需要进行故障排除。


解决此问题的另一种方法是编写自己的安装脚本。这是最灵活的选项，但要权衡花费更多时间来构建自定义解决方案是否值得。


#### 机密信息问题


Git 旨在跟踪更改。如果你在 Git 存储库中存储密码或 API 密钥之类的机密信息，则会比较麻烦，并且需要重写 Git 历史记录以删除该机密信息。如果你的存储库是公开的，那么如果其他人下载了你的存储库，你的机密信息将不再保密。仅这个问题就会阻止许多人与公共世界共享其点文件。


#### 多设备配置问题


问题不在于如何将配置拉到多个设备，而是当你有多个需要不同配置的设备的问题。大多数人通过使用不同的文件夹或使用不同的<ruby> 复刻 <rt>  fork </rt></ruby>来处理此问题。这使得难以在不同设备和角色集之间共享配置。


### Chezmoi 是如何干的


Chezmoi 是一种考虑了以上问题的用于管理点文件的工具，它不会盲目地从存储库复制或符号链接文件。 Chezmoi 更像是模板引擎，可以根据系统变量、模板、机密信息管理器和 Chezmoi 自己的配置文件来生成你的点文件。


#### Chezmoi 入门


目前，Chezmoi 并不在 Fedora 的默认软件库中。你可以使用以下命令下载 Chezmoi 的当前版本。



```
$ sudo dnf install https://github.com/twpayne/chezmoi/releases/download/v1.7.17/chezmoi-1.7.17-x86_64.rpm
```

这会将预打包的 RPM 安装到你的系统中。


让我们继续使用以下方法创建你的存储库：



```
$ chezmoi init
```

它将在 `~/.local/share/chezmoi/` 中创建你的新存储库。你可以使用以下命令轻松地切换到该目录：



```
$ chezmoi cd
```

让我们添加第一个文件：



```
chezmoi add ~/.bashrc
```

这将你的 `.bashrc` 文件添加到 chezmoi 存储库。


注意：如果你的 `.bashrc` 文件实际上是一个符号链接，则需要添加 `-f` 标志以跟随它来读取实际文件的内容。


现在，你可以使用以下命令编辑该文件：



```
$ chezmoi edit ~/.bashrc
```

现在让我们添加一个私有文件，这是一个具有 600 或类似权限的文件。我在 `.ssh/config` 中有一个文件，我想通过使用如下命令添加它：



```
$ chezmoi add ~/.ssh/config
```

Chezmoi 使用特殊的前缀来跟踪隐藏文件和私有文件，以解决 Git 的限制。运行以下命令以查看它：



```
$ chezmoi cd
```

**请注意，标记为私有的文件实际上并不是私有的，它们仍会以纯文本格式保存在你的 Git 存储库中。稍后会进一步解释。**


你可以使用以下方法应用任何更改：



```
$ chezmoi apply
```

并使用如下命令检查有什么不同：



```
$ chezmoi diff
```

#### 使用变量和模板


要导出 Chezmoi 可以收集的所有数据，请运行：



```
$ chezmoi data
```

其中大多数是有关用户名、架构、主机名、操作系统类型和操作系统名称的信息。但是你也可以添加我们自己的变量。


继续，运行：



```
$ chezmoi edit-config
```

然后输入以下内容：



```
[data]
         email = "fedorauser@example.com"
         name = "Fedora Mcdora"
```

保存文件，然后再次运行 `chezmoi data`。你将在底部看到你的电子邮件和姓名已经添加成功。现在，你可以将这些与 Chezmoi 的模板一起使用。运行：



```
$ chezmoi add  -T --autotemplate ~/.gitconfig
```

来将你的 `.gitconfig` 作为模板添加到 Chezmoi 中。如果 Chezmoi 成功地正确推断了模板，你将获得以下信息：



```
[user]
         email = "{{ .email }}"
         name = "{{ .name }}"
```

如果没有，则可以将文件更改为这样。


使用以下方法检查文件：



```
$ chezmoi edit ~/.gitconfig
```

然后使用：



```
$ chezmoi cat ~/.gitconfig
```

来查看 Chezmoi 为此文件生成什么。我生成的示例如下：



```
[root@a6e273a8d010 ~]# chezmoi cat ~/.gitconfig
[user]
    email = "fedorauser@example.com"
    name = "Fedora Mcdora"
[root@a6e273a8d010 ~]#
```

它将在我们的 Chezmoi 配置中生成一个充满变量的文件。你也可以使用变量执行简单的逻辑语句。一个例子是：



```
{{- if eq .chezmoi.hostname "fsteel" }}
# 如果主机名为 "fsteel" 才包括此部分
{{- end }}
```

请注意，要使其正常工作，该文件必须是模板。你可以通过查看文件是否在 `chezmoi cd` 中的文件名后附加 `.tmpl` 或使用 `-T` 选项读取文件来进行检查。


#### 让机密信息保持机密


要对设置进行故障排除，请使用以下命令。



```
$ chezmoi doctor
```

这里重要的是它还向你显示了[所支持的密码管理器](https://www.chezmoi.io/docs/how-to/#keep-data-private)。



```
[root@a6e273a8d010 ~]# chezmoi doctor
 warning: version dev
      ok: runtime.GOOS linux, runtime.GOARCH amd64
      ok: /root/.local/share/chezmoi (source directory, perm 700)
      ok: /root (destination directory, perm 550)
      ok: /root/.config/chezmoi/chezmoi.toml (configuration file)
      ok: /bin/bash (shell)
      ok: /usr/bin/vi (editor)
 warning: vimdiff (merge command, not found)
      ok: /usr/bin/git (source VCS command, version 2.25.1)
      ok: /usr/bin/gpg (GnuPG, version 2.2.18)
 warning: op (1Password CLI, not found)
 warning: bw (Bitwarden CLI, not found)
 warning: gopass (gopass CLI, not found)
 warning: keepassxc-cli (KeePassXC CLI, not found)
 warning: lpass (LastPass CLI, not found)
 warning: pass (pass CLI, not found)
 warning: vault (Vault CLI, not found)
 [root@a6e273a8d010 ~]#
```

你可以使用这些客户端，也可以使用[通用客户端](https://www.chezmoi.io/docs/how-to/#use-a-generic-tool-to-keep-your-secrets)，也可以使用系统的[密钥环](https://www.chezmoi.io/docs/how-to/#use-a-keyring-to-keep-your-secrets)。


对于 GPG，你需要使用以下命令将以下内容添加到配置中：



```
$ chezmoi edit-config
```


```
[gpg]
   recipient = "<Your GPG keys Recipient"
```

你可以使用：



```
$ chezmoi add --encrypt
```

来添加任何文件，这些文件将在你的源存储库中加密，并且不会以纯文本格式公开。Chezmoi 会在应用时自动将其解密。


我们也可以在模板中使用它们。例如，存储在 [Pass](https://fedoramagazine.org/using-pass-to-manage-your-passwords-on-fedora/)（已在 Fedora 杂志上介绍）中的机密令牌。继续，生成你的机密信息。


在此示例中，它称为 `githubtoken`：



```
rwaltr@fsteel:~] $ pass ls
 Password Store
 └── githubtoken
 [rwaltr@fsteel:~] $
```

接下来，编辑你的模板，例如我们之前创建的 `.gitconfig` 并添加以下行。



```
token = {{ pass "githubtoken" }}
```

然后让我们使用检查：



```
$ chezmoi cat ~/.gitconfig
```


```
[rwaltr@fsteel:~] $ chezmoi cat ~/.gitconfig
 This is Git's per-user configuration file.
 [user]
           name = Ryan Walter
           email = rwalt@pm.me
           token = mysecrettoken
 [rwaltr@fsteel:~] $
```

现在，你的机密信息已在密码管理器中妥善保护，你的配置可以公开共享而没有任何风险！


### 最后的笔记


这里仅仅涉及到表面。请访问 [Chezmoi 的网站](https://www.chezmoi.io/)了解更多信息。如果你正在寻找有关如何使用 Chezmoi 的更多示例，作者还可以公开了他的[点文件](https://github.com/twpayne/dotfiles)。




---


via: <https://fedoramagazine.org/take-back-your-dotfiles-with-chezmoi/>


作者：[Ryan Walter](https://fedoramagazine.org/author/rwaltr/) 选题：[lujun9972](https://github.com/lujun9972) 译者：[wxy](https://github.com/wxy) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
In Linux, dotfiles are hidden text files that are used to store various configuration settings for many such as Bash and Git to more complex applications like i3 or VSCode.

Most of these files are contained in the *~/.config *directory or right in the home directory. Editing these files allows you to customize applications beyond what a settings menu may provide, and they tend to be portable across devices and even other Linux distributions. But one talking point across the Linux enthusiast community is how to manage these dotfiles and how to share them.

We will be showcasing a tool called [Chezmoi](https://www.chezmoi.io/) that does this task a little differently from the others.

## The history of dotfile management

If you search [GitHub for dotfiles](https://github.com/search?q=dotfiles&type=Repositories), what you will see are over 100k repositories after one goal: Store people’s dotfiles in a shareable and repeatable manor. However, other than using git, they store their files differently.

While Git has solved code management problems that also translates to config file management, It does not solve how to separate between distributions, roles (such as home vs work computers) secrets management, and per device configuration.

Because of this, many users decide to craft their own solutions, and the community has responded with multiple answers over the years. This article will briefly cover some of the solutions that have been created.

### Experiment in an isolated environment

Do you want to try these below solutions quickly in a contained environment? Run:

$ podman run --rm -it fedora

… to create a Fedora container to try the applications in. This container will automatically delete itself when you exit the shell.

### The install problem

If you store your dotfiles in Git repository, you will want to make it easy for your changes to automatically be applied inside your home directory, the easiest way to do this at first glance is to use a symlink, such as *ln -s ~/.dotfies/bashrc ~/.bashrc*. This will allow your changes to take place instantly when your repository is updated.

The problem with symlinks is that managing symlinks can be a chore. Stow and [RCM (covered here on Fedora Magazine)](https://fedoramagazine.org/managing-dotfiles-rcm/) can help you manage those, but these are not seamless solutions. Files that are private will need to be modified and chmoded properly after download. If you revamp your dotfiles on one system, and download your repository to another system, you may get conflicts and require troubleshooting.

Another solution to this problem is writing your own install script. This is the most flexible option, but has the tradeoff of requiring more time into building a custom solution.

### The secrets problem

Git is designed to track changes. If you store a secret such as a password or an API key in your git repository, you will have a difficult time and will need to rewrite your git history to remove that secret. If your repository is public, your secret would be impossible to recover if someone else has downloaded your repository. This problem alone will prevent many individuals from sharing their dotfiles with the public world.

### The multi-device config problem

The problem is not pulling your config to multiple devices, the problem is when you have multiple devices that require different configuration. Most individuals handle this by either having different folders or by using different forks. This makes it difficult to share configs across the different devices and role sets

## How Chezmoi works

Chezmoi is a tool to manage your dotfiles with the above problems in mind, it doesn’t blindly copy or symlink files from your repository. Chezmoi acts more like a template engine to generate your dotfiles based on system variables, templates, secret managers, and Chezmoi’s own config file.

### Getting Started with Chezmoi

Currently Chezmoi is not in the default repositories. You can download the current version of Chezmoi as of writing with the following command.

$ sudo dnf install https://github.com/twpayne/chezmoi/releases/download/v1.7.17/chezmoi-1.7.17-x86_64.rpm

This will install the pre-packaged RPM to your system.

Lets go ahead and create your repository using:

$ chezmoi init

It will create your new repository in *~/.local/share/chezmoi/*. You can easily cd to this directory by using:

$ chezmoi cd

Lets add our first file:

chezmoi add ~/.bashrc

… to add your bashrc file to your chezmoi repository.

Note: if your bashrc file is actually a symlink, you will need to add the -f flag to follow it and read the contents of the real file.

You can now edit this file using:

$ chezmoi edit ~/.bashrc

Now lets add a private file, This is a file that has the permissions 600 or similar. I have a file at .ssh/config that I would like to add by using

$ chezmoi add ~/.ssh/config

Chezmoi uses special prefixes to keep track of what is a hidden file and a private file to work around Git’s limitations. Run the following command to see it:

$ chezmoi cd

**Do note that files that are marked as private are not actually private, they are still saved as plain text in your git repo. More on that later.**

You can apply any changes by using:

$ chezmoi apply

and inspect what is different by using

$ chezmoi diff

### Using variables and templates

To export all of your data Chezmoi can gather, run:

$ chezmoi data

Most of these are information about your username, arch, hostname, os type and os name. But you can also add our own variables.

Go ahead and run:

$ chezmoi edit-config

… and input the following:

[data] email = "fedorauser@example.com" name = "Fedora Mcdora"

Save your file and run chezmoi data again. You will see on the bottom that your email and name are now added. You can now use these with templates with Chezmoi. Run:

$ chezmoi add -T --autotemplate ~/.gitconfig

… to add your gitconfig as a template into Chezmoi. If Chezmoi is successful in inferring template correctly, you could get the following:

[user] email = "{{ .email }}" name = "{{ .name }}"

If it does not, you can change the file to this instead.

Inspect your file with:

$ chezmoi edit ~/.gitconfig

After using

$ chezmoi cat ~/.gitconfig

… to see what chezmoi will generate for this file. My generated example is below:

[root@a6e273a8d010 ~]# chezmoi cat ~/.gitconfig [user] email = "fedorauser@example.com" name = "Fedora Mcdora" [root@a6e273a8d010 ~]#

It will generate a file filled with the variables in our chezmoi config.

You can also use the varibles to perform simple logic statements. One example is:

{{- if eq .chezmoi.hostname "fsteel" }} # this will only be included if the host name is equal to "fsteel" {{- end }}

Do note that for this to work the file has to be a template. You can check this by seeing if the file has a “.tmpl” appended to its name on the file in *chezmoi cd*, or by readding the file using the -T option

### Keeping secrets… secret

To troubleshoot your setup, use the following command.

$ chezmoi doctor

What is important here is that it also shows you the [password managers it supports](https://www.chezmoi.io/docs/how-to/#keep-data-private).

[root@a6e273a8d010 ~]# chezmoi doctor warning: version dev ok: runtime.GOOS linux, runtime.GOARCH amd64 ok: /root/.local/share/chezmoi (source directory, perm 700) ok: /root (destination directory, perm 550) ok: /root/.config/chezmoi/chezmoi.toml (configuration file) ok: /bin/bash (shell) ok: /usr/bin/vi (editor) warning: vimdiff (merge command, not found) ok: /usr/bin/git (source VCS command, version 2.25.1)ok: /usr/bin/gpg (GnuPG, version 2.2.18) warning: op (1Password CLI, not found) warning: bw (Bitwarden CLI, not found) warning: gopass (gopass CLI, not found) warning: keepassxc-cli (KeePassXC CLI, not found) warning: lpass (LastPass CLI, not found) warning: pass (pass CLI, not found) warning: vault (Vault CLI, not found)[root@a6e273a8d010 ~]#

You can use either of these clients, or a [generic client](https://www.chezmoi.io/docs/how-to/#use-a-generic-tool-to-keep-your-secrets), or your system’s [Keyring](https://www.chezmoi.io/docs/how-to/#use-a-keyring-to-keep-your-secrets).

For GPG, you will need to add the following to your config using:

$ chezmoi edit-config

[gpg] recipient = "<Your GPG keys Recipient"

You can use:

$ chezmoi add --encrypt

… to add any files, these will be encrypted in your source respository and not exposed to the public world as plain text. Chezmoi will automatically decrypt them when applying.

We can also use them in templates. For example, a secret token stored in [Pass (covered on Fedora Magazine)](https://fedoramagazine.org/using-pass-to-manage-your-passwords-on-fedora/). Go ahead and generate your secret.

In this example, it’s called “githubtoken”:

rwaltr@fsteel:~] $ pass ls Password Store └── githubtoken [rwaltr@fsteel:~] $

Next, edit your template, such as your .gitconfig we created earlier and add this lines.

token = {{ pass "githubtoken" }}

Then lets inspect using*:*

$ chezmoi cat ~/.gitconfig

[rwaltr@fsteel:~] $ chezmoi cat ~/.gitconfig This is Git's per-user configuration file. [user] name = Ryan Walter email = rwalt@pm.me token = mysecrettoken [rwaltr@fsteel:~] $

Now your secrets are properly secured in your password manager, your config can be publicly shared without risk!

## Final notes

This is only scratching the surface. Please check out [Chezmoi’s website](https://www.chezmoi.io/) for more information. The author also has his [dotfiles public](https://github.com/twpayne/dotfiles) if you are looking for more examples on how to use Chezmoi.

## Yaroslav

To store dotfiles in a VCS it’s enough to have a bare git repository (see https://www.atlassian.com/git/tutorials/dotfiles for the full recipe).

Your tool seems to contradict the UNIX philosophy that there should be one instrument for each task. To create dotfiles from templates seems an ununderstandable overhead here.

## Paul W. Frields

## Yaroslav

What exactly in your comment should be not obvious for Linux users?

Linux belongs to the UNIX family. See https://en.wikipedia.org/wiki/Linux

Yes, I’m aware of the existence different philosophies. UNIX philosophy is pretty good though. Care to explain what philosophy or good programming patterns this tool follows?

## Sebastiaan Franken

No, it doesn’t. Linux is a UNIX-like (with emphasis on the like part) OS family. It’ s

notpart of the UNIX family.Also, “good programming patterns” seem to change every six months or so…

## Ryan Walter

I would disagree, I would say it embraces the Unix philosophy.

It does one thing well, it builds your dotfiles based on a template. It does not solve encryption. It uses GPG to do that, it does not solve password management. It uses password managers for that. It does not solve code revisioning. It uses Git (or any of your choosing)

I was originally using git with stow. Which would be similar to your config alias. But when I was installing to other systems. I would have to chmod all my private files. I also was attempting to branches to separate my roles. But found that managing the commits between the two branches a bit of a chore.

## ergr

I have symlink to my config file for example .vimrc

mc alvways ask me breaking simlink or no. How tell mc tho stop ask me? In normal hard link too!

## aairey

I am using dotdrop, which also does many of these except the secrets management and templating (AFAIK).

Seems I need to look into chezmoi, thanks for sharing!

## Stephen

A timely article for me as I was in the process of cleaning up my dot files again. I was using stow, but had seen some drawbacks with it over time. I set up chezmoi, and have it covering the primary dot files with intentions of adding all of them in eventually. The biggest issue I am having currently is trying to stop old habits from interfering with it, like editing a file with Vim instead of chezmoi edit. I use Silverblue, so it would be nice if this was layered from an official package repo or COPR at least. Ideally, it should be able to be a flatpak quite easily.

## Ryan Walter

Have you started using templates yet? If you edited your file and it’s not a template. You can re-add it using Chezmoi add and it would achieve the same affect.

This took me some time to adapt to as well. But Chezmoi edit is mainly important for your template files. Since your target will be different from your source.

Packaging it for Fedora is something I’m currently looking at. But I have not packaged something before and might take me some time.

## Stephen

Hello,

Yes I have my .gitconfig setup as a template, and I had already been working on a .zshrc template prior to your article, so like I said timely. I have my pgp key setup for encryption as well. It seems promising, and a better thought out solution thanthe usual methods of dot file care taking.

The packaging would be good since it becomes a problem at update time on Silverblue, basically I need to update it separately and manually each time while I choose to use it. Official, even COPR repos will get automatically checked for updates, plus the added benefit of being built with everything else at the same time with the same versions of lib’s.

## Patrick O'Callaghan

I have a minor nit: Linux (and UNIX) have no such thing as “hidden” files. Dotfiles are only “hidden” in the sense that by default they don’t appear when you run ‘ls’ and some other utilities that follow the same convention. They don’t have some magical special property that hides them from anything else. Although old hands know this perfectly well, it’s better to avoid this terminology so as not to confuse newcomers.

## Klaus Ferreira

Thanks for the article. I was about to get crazy with my dot files hahaha BTW, is it me or you can only use diff BEFORE applying? I mean, if I follow the article (using diff AFTER applying) I got nothing as output.

## Ryan Walter

You are correct. Diff should come before apply. Otherwise the states match and there is nothing that is different! 🙂 My bad