ys memos

Blog

C++でGitRootを探す方法


c++

2020/11/19

Git でプロジェクト管理している時、プログラム内で Git ルートディレクトリを参照したいときがあると思う。 そんな時は再帰を活用すると楽にできる。


Ubuntu 上でboost::filesystemを利用した。 他の言語やライブラリでも同じアルゴリズムで Git ルートを探すことができる。

Ubuntu20.04LTS
g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
Boost 1.71

  1. 探索開始(SearchDir:カレントディレクトリ)
  2. SearchDir に.gitが含まれていれば SearchDir を返す
  3. 親ディレクトリがユーザのホームであれば空のパスを返す
  4. 親ディレクトリ SearchDir として 2 に戻る

#include <iostream>

#include <boost/filesystem.hpp>
#include <boost/filesystem/operations.hpp>
namespace fs = boost::filesystem;

boost::filesystem::path find_git_root (boost::filesystem::path directory) {
  for (auto& filename : boost::filesystem::directory_iterator (directory)) {
    if (filename.path ().leaf ().string () == ".git") {
      return directory;
    }
  }

  if (directory.branch_path () == getenv("HOME")) {
    return boost::filesystem::path ();
  }

  return find_git_root (directory.branch_path ());
}

int main (int argc, char** argv) {
  fs::path git_root = find_git_root (fs::current_path ());
  std::cout << "GIT ROOT DIR : " << git_root << std::endl;
  return 0;
}

こちらにソースコードを公開した。

CmakeLists.txtも合わせて公開してあるので、クローンすれば問題なく動作するはず

関連タグを探す