LoginSignup
5
5

More than 5 years have passed since last update.

libgit2のrubyバインディングruggedでファイル名が無視されるか判定する

Posted at

はじめに

あるファイル名がgitレポジトリで無視されるのかどうかを判定したいというニーズが仕事でありまして、libgit2のrubyバインディングruggedにプルリクエストを送ったら早速マージされたので、使い方を紹介します。

サンプルコードは
https://github.com/hnakamur/rugged-path-ignored-example
に置いてあります。MITライセンスです。

Ruggedについて

Ruggedlibgit2のRubyバインディングです。

Ruby Toolboxのgit Toolsカテゴリを見ると、一番人気はGritなのですが、GitHubのページには"Grit is no longer maintained. Check out libgit2/rugged."と書かれています。

ちなみに、Githugは"An interactive way to learn git."とのことでGitを使うためのライブラリではなく、Gitをインタラクティブに学習するための別用途のものです。ruby-gitはgitコマンドを実行するラッパ形式のライブラリです。

Gemfileでの指定方法

Ruggedに説明がありますが、以下のように指定します。

gem 'rugged', git: 'git://github.com/libgit2/rugged.git', branch: 'development', submodules: true

submodules: trueの指定によってlibgit2をgithubから取得してコンパイルするようになっています。最初この指定を忘れていたら、homebrewで入れたlibgit2 0.20.0を使ってコンパイルエラーになってしまいました。

あとはbundleでruggedをインストールします。

bundle install --path vendor/bundle

サンプルコード

例えば

gitignore
.*
!.ht*
/vendor/*

のように指定した場合、

test.rb
require 'rugged'

repo = Rugged::Repository.new '.'
puts repo.path_ignored?('.DS_Store') # true
puts repo.path_ignored?('.htaccess') # false

のようなソースコードを

bundle exec ruby test.rb

として実行すると、

true
false

のように出力されます。ファイルの実体が存在する必要はなくて、単に指定したファイル名が.gitignoreの設定に照らしあわせて無視されるかどうかを判定できるようになっています。Rugged::Repository#path_ignored?の実装はlibgit2のgit_ignore_path_is_ignoredを単に呼び出しているだけです。

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5