k4200’s notes and thoughts

Programmer side of k4200

JGitその2

前回、JGitのインストールとかについて少し書いた。

今回は使い方について簡単に。サンプルコードは例によってScalaだけど、Javaでも文法が違う以外は全く一緒。Javaプログラマーはこれを機にScalaを勉強してもいいんじゃないかな。

前準備

import org.eclipse.jgit._
import lib._
import api.Git
import storage.file.{FileRepository, FileRepositoryBuilder}
import transport.{Transport, RefSpec, RemoteConfig, URIish}

// 例えばレポジトリが /home/user/proj-a/.git だとする。
val projPath = "/home/user/proj-a"
val gitosisRepo =
    builder.setGitDir(projPath + "/" + Constants.DOT_GIT)
    .readEnvironment().findGitDir().build()
val git = new Git(gitosisRepo)


後は、このgitというオブジェクトを使って色々操作できる。基本パターンは以下の通り。

// /home/user/proj-a/dir1/file1 というファイルを変更したとする。
git.add().addFilepattern("dir1/file1").call()
git.commit().setMessage(message).call()

Gitクラスのaddとかcommitとかのメソッドを呼び出すと、AddCommandとかCommitCommandとかいうクラスのインスタンスが返される。それらは全てCallableインターフェースを実装したクラス。

で、後はメソッドチェーンでgitコマンドのパラメータとして渡すような値を設定していき、最後にcallメソッドを呼ぶ。

今回はこのくらい。次回は各コマンドについて細かく書くかも。