public class GitCommandSpike
import java.io.*; public class GitCommandSpike { public static void main(String...args) { GitCommandSpike spike = new GitCommandSpike("repos"); System.out.println(spike.version()); System.out.println(spike.status()); System.out.println(spike.commit("コミットしてみるテスト")); System.out.println(spike.status()); //always returns 1 System.out.println(spike.log()); } final File repository; public GitCommandSpike(String repository) { this.repository = new File(repository); } public int version() { return exec("/usr/local/git/bin/git", "--version"); } public int status() { return exec("/usr/local/git/bin/git", "status"); } public int init() { return exec("/usr/local/git/bin/git", "log"); } public int commit(String message) { return exec("/usr/local/git/bin/git", "commit", "-am", "\""+message+"\""); } public int log() { return exec("/usr/local/git/bin/git", "log"); } Process buildProcess(String...args) { ProcessBuilder pb = new ProcessBuilder(args); pb.redirectErrorStream(true); pb.directory(repository); try { return pb.start(); } catch (IOException e) { throw new RuntimeException(e); } } int exec(String...args) { Process p = buildProcess(args); try { int ret = p.waitFor(); InputStream in = p.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line; while ((line = br.readLine())!=null) System.out.println(line); return ret; } catch (Exception e) { throw new RuntimeException(e); } } }
Process#getInputStream()で取得したストリームはいつ閉じられるんだろう…。
出力結果は下みたいな感じ。
git version 1.6.3.3 0 # On branch master nothing to commit (working directory clean) 1 # On branch master nothing to commit (working directory clean) 1 # On branch master nothing to commit (working directory clean) 1 commit 57ff7e37f3ff6d772f9138fef1d60cc983fc42e1 Author: katzchang <katzchang@gmail.com> Date: Wed Jul 21 10:33:02 2010 +0900 "コミットしてみるテスト" commit cc52dd15f4a22a721e4fff44216269bd332f5431 Author: katzchang <katzchang@gmail.com> Date: Sun Jul 18 05:04:19 2010 +0900 add with AddCommand commit c973f38527316ffb09e45aaca3281c5c4d299b8c Author: katzchang <katzchang@gmail.com> Date: Sun Jul 18 02:18:18 2010 +0900 コミットしたお 0
とりあえず動くよ、程度のものですので。