Skip to content

备份 dotfiles

你的电脑上可能安装了很多工具,每个工具都有自己的配置文件,存放在不同的位置。如果你刚买了一台新电脑,或者只是在现有电脑上重装了操作系统,你是否想从头开始重新设置所有的配置文件?

目标

  • 通过 Git 管理和备份电脑上的各种配置文件
  • 在两台不同的机器之间共享同一套 dotfiles
  • 系统:
    • Windows 10, PowerShell 7.5.3 Preview
    • MacOS, iTerm2
  • 方法:通过一个裸 Git 仓库 (bare Git repository)

跟踪的文件

  • .zshrc
  • .vimrc
  • AppData/Local/nvim
  • AppData/Local/nvim-from-scratch

备份

  1. 在 Windows 上,创建一个新文件夹 $HOME/dotfiles,并运行 git init --bare 将其初始化为一个裸仓库(没有工作目录),用于跟踪你需要管理的配置文件。

  2. 将基本的 git 命令转换为 gitbare 命令,即在 PowerShell 中运行 gitbare 而不是基本的 git 时,Git 会自动将 $HOME/dotfiles 视为仓库,并将整个 $HOME 目录视为工作区。要完成此替换,只需在 PowerShell 中运行 code $PROFILE,使用 VS Code 打开配置文件,并添加以下函数:

    ps1
    function gitbare {
    git --git-dir=$HOME/dotfiles --work-tree=$HOME $args
    }
  3. 完成第 2 步后,当我们需要处理我们的 dotfiles 仓库时,我们可以使用改造后的 gitbare addgitbare commitgitbare remote,而不是原来的 git addgit commitgit remote

  4. 在 GitHub 上创建一个新仓库,https://github.com/user-name/dotfiles

    sh
    gitbare remote add origin https://github.com/user-name/dotfiles.git
    gitbare branch -M main
    gitbare push -u origin main
  5. 现在你可以从你的 $HOME 目录中选择性地添加、提交和推送配置文件到你的远程 GitHub 仓库进行备份。

本地仓库从零重建

远程仓库已经存在,也包含之前推送过的仓库文件夹和文件。现在本地仓库删除,完全从零开始重建。当尝试运行 gitbare push 触发以下报错:

sh
fatal: The current branch main has no upstream branch.
To push the current branch and set the remote as upstream, use

    git push --set-upstream origin main

To have this happen automatically for branches without a tracking
upstream, see 'push.autoSetupRemote' in 'git help config'.

根据提示,运行 gitbare push --set-upstream origin main 之后,旋即触发以下报错:

sh
error: src refspec main does not match any
error: failed to push some refs to 'https://github.com/alowree/dotfiles.git'

没有更好的办法,只好手动删除运程仓库,再重新推送。

拉取

待测试...

参考

最近更新