LoginSignup
35
37

More than 5 years have passed since last update.

Java で Git を操作する

Last updated at Posted at 2014-11-13

とある Git リポジトリからファイルをごっそり持ってきて加工したあげく別システムに取り込むバッチ処理を作る必要があったので触ってみました。

Jgit とは?

  • Java で Git を操作するためのライブラリ
    • Eclipse 用の Git プラグイン Egit で使われているらしい
    • ので Eclipse Foundation が開発しているらしい

やりたいこと

  • リモートリポジトリを含めたブランチ一覧の取得 (git branch -a)
  • ローカルブランチの切り替え (git checkout ほげほげ)
  • ローカルブランチとリモートブランチのマージ (git pull もしくは git fetch & git merge)

サンプルコード

  • 前提
    • Jgit ライブラリは適宜ダウンロードするなり maven や gradle で使えるようにしておく
      • 下記コードは Jgit の Core Library だけで動くはず
  • 操作するローカルリポジトリは git clone 実行済み (以下例だと /ika に clone した状態)
JgitSample.java
public class JgitSample {
    public static void main(String[] args) throws Exception {
        // ローカルリポジトリの指定など
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(new File("/ika/" + Constants.DOT_GIT)).readEnvironment().findGitDir().build();

        // Git オブジェクト作成 (このオブジェクトを操作していろいろする)
        Git git = new Git(repository);
        // まず fetch してブランチの情報を最新にしておく
        try {
            git.fetch().setRemote(Constants.DEFAULT_REMOTE_NAME).call();
        } catch (GitAPIException e) {
                throw new RuntimeException(e);
        }

        // ブランチの切り替え(リモートにあるやつ)
        try {
            // 初めてリモートリポジトリを checkout する場合
            git.checkout().setCreateBranch(true).setName("ブランチ名")
                .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.SET_UPSTREAM)
                .setStartPoint("リポジトリ名" + "ブランチ名").call(); # origin/ブランチ名 みたいに設定する

        } catch (RefAlreadyExistsException e) {
            // 2回目以降(checkout 済みだと上記例外が投げられるっぽいので)
            try {
                git.checkout().setName("ブランチ名").call();
                git.pull().call();
            } catch (GitAPIException e1) {
                throw new RuntimeException(e);
            }
        } catch (GitAPIException e) {
            throw new RuntimeException(e);
        }

        // ブランチ名の一覧取得(Ref の getName()で「refs/remotes/origin/master」のように取得できる)
        List<Ref> branchList = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();
    }
}
35
37
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
35
37