Unknown Me

我的多项目管理

随着时间推移,需要管理的项目越来越多,而且还要考虑区分管理个人项目与公司项目,这里记录一下我个人的管理方案。

以下项目都是指 git 管理的项目。

# 存放路径

我曾经遇到的烦恼:

  1. 这个库我 clone 下来要放到哪里去?
  2. 这个库我曾经 clone 过到本地吗?

遇到很多同学会把所有项目都放到同一个目录里,比如 ~/Code,这样确实可以很容易找到曾经的项目,但缺陷也很明显:

  1. 没有分类,所以很难分开不同的来源(这个库是 github 来的还是 gitlab 来的?)
  2. 遇到重名项目就麻烦了,打个比方,我想为开源项目 facebook/react 贡献代码,所以我 fork 了一份 myname/react ,当我想把这两个项目都 clone 下来时就发现重名..

当然解决重名好办,引入 "命名空间" 可破,git 项目天然就有命名空间,将 remote url 格式化成 github.com/facebook/react 就是唯一的,所以我也把这个映射关系用在我本地硬盘上,直接解决了上面的困扰~

$ git clone https://github.com/facebook/react ~/Code/github.com/facebook/react

我最终还写一段 zsh 脚本 gitcd.plugin.zsh (opens new window) 来实现这个效果:

  1. 分析 remote url,克隆仓库到上述规则的目录里,并切换到这个目录
  2. 如果目录已经存在,就直接切换到这个目录
$ gitcd https://github.com/facebook/react
# 相当于以下两句
$ git clone https://github.com/facebook/react ~/Code/github.com/facebook/react
$ cd ~/Code/github.com/facebook/react

# git config

一般来说,在不同场景下会有不同的身份,比如我会在 GitHub 上使用网名,而在公司内部 gitlab 使用真名。所以 git config 需要区分不同的 user.name 和 user.email。

虽然可以每个 git 项目都敲一次 git config user.name xxx,但是这很麻烦,也容易忘记。 我试过好几次 commit 完看 git log 才发现自己忘记单独配置而直接读了全局的 git 配置,将我的网名推到了公司仓库。

万幸发现了 git 2.13.0 以后有一个叫 conditional includes (opens new window) 的功能,可以实现不同目录自动使用不同的 gitconfig,配置一次就够了:

  1. 删掉 ~/.gitconfig 里的 user 章节,也就是不使用全局配置了

  2. 增加 includeIf 配置,意思是这两个目录下分别读不同的配置文件

    # ~/.gitconfig
    [includeIf "gitdir:~/Code/Personal/"]
      path = .gitconfig-personal
    [includeIf "gitdir:~/Code/Work/"]
      path = .gitconfig-work
    
  3. 然后分别创建不同的配置文件,填写独立的信息

    # ~/.gitconfig-work
    [user]
    name = My name in company
    email = name@company.com
    
    # ~/.gitconfig-personal
    [user]
    name = My GitHub username
    email = name@mail.com
    
  4. 这样在不同的目录下,就可以很放心的提交了,不用再担心会不会搞混了网络身份,哦耶~

# ssh key

同样地,多个 ssh key 也是需要管理的

  1. 需要共存
  2. push 时候自动选私钥

步骤

  1. 分别生成不同网站的密钥对

    # gitlab.com
    $ ssh-keygen -f ~/.ssh/id_rsa_gitlab -t rsa -N '' -C "A@mail.com"
    # # github.com
    $ ssh-keygen -f ~/.ssh/id_rsa_github -t rsa -N '' -C "B@mail.com"
    
    # 参数解释
    # -f : Specify file to output
    # -t rsa : Specify the type of key to be generated
    # -C : the comment
    # -N: Specify the new passphrase
    
  2. 在~/.ssh/目录下新建config文件,用于配置各个公私钥对应的主机

    # gitlab.com
    Host gitlab.com
    HostName gitlab.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa_gitlab
    
    # github.com
    Host github.com
    HostName github.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa_github
    
  3. 在各个网站配置公钥

  4. 最后校验

    $ ssh -T git@github.com
    

# 参考链接