JGitでGistを編集する

やりたいこと

おすすめのお店をGistで管理しているのですが、外出先でスマホしかないときだと編集するのが大変です。 そこで、Gistの表を更新するアプリを作ろうと思ったのですが、その前にJGitを使ってGistが編集できるか確かめようと思います。

gist.github.com

JGitとは

Javaのプログラミング上でgitの操作をするためのライブラリです。Eclipse Foundationが作っているようですが、私は普段はIntellijを使ってます。(←どうでもいい)

pom.xmlに以下を追加するだけですぐに使えるようになります。

<!-- https://mvnrepository.com/artifact/org.eclipse.jgit/org.eclipse.jgit -->
<dependency>
    <groupId>org.eclipse.jgit</groupId>
    <artifactId>org.eclipse.jgit</artifactId>
    <version>5.0.0.201806131550-r</version>
</dependency>

Git - JGit

JGit | The Eclipse Foundation

やったこと

1 . git clone

2 . 行の追加

3 . git add & git commit

4 . git push

1. git clone

cloneしたいgistのurlをsetURI(repositoryURI)で指定して、cloneRepository()をすれば、setDirectory(new File(localRepositoryPath))で指定したディレクトリにcloneされます。すでに指定したディレクトリにファイルがあるとエラー(Destination path "repository" already exists and is not an empty directory)になってしまうので、アプリケーションを実行するたびにディレクトリを削除するようにしています。

// delete local dir and clone gist to local dir
String localRepositoryPath = "/tmp/repository";
File localRepository = new File(localRepositoryPath);
FileUtils.deleteDirectory(localRepository);
localRepository.mkdir();
Git.cloneRepository().setURI(repositoryURI).setDirectory(new File(localRepositoryPath)).call();

2. 行の追加

追加したいファイルを開いて、書き込んでいるだけです。

String shopFile = localRepositoryPath + "/sample.md";
FileWriter filewriter = new FileWriter(new File(shopFile), true);
filewriter.write("| sample2 | http://local.com | \n");
filewriter.close();

3. git add & git commit

repositoryBuilderで操作するrepositoryを指定すると、そのrepositoryに対してgit.add()git.commit()出来るようになります。 repositoryの指定は.gitファイルを指定しないといけないので注意が必要です。

// git add command and commit command
FileRepositoryBuilder repositoryBuilder = new FileRepositoryBuilder();
Repository repository = repositoryBuilder.setGitDir(new File(localRepositoryPath + "/.git"))
        .readEnvironment()
        .findGitDir()
        .setMustExist(true)
        .build();
Git git = new Git(repository);
git.add().addFilepattern("sample.md").call();
git.commit().setMessage("add new shop").call();

4. git push

pushするには認証情報が必要なので、githubでAccessTokenを発行し、それを使ってpushするようにしました。

// git push
CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider( "using_accesstoken", "" );
git.push().setCredentialsProvider(credentialsProvider).call();

AccessTokenは『Settings』->『Developer settings』->『Personal access tokens』で取得可能です。

f:id:qphsmt:20180624013204p:plain

確認

アプリケーションを実行すると行が追加されました!

gist.github.com