最近爱上了Git,当然不能忽略jGit啦

好吧废话少说,直接上代码先:

package net.wendal.jgit;

import java.io.File;
import java.io.FileWriter;

import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.revwalk.RevCommit;

public class JGit {

    public static void main(String[] args) throws Throwable {
        File root = new File("gitme");
        if(!root.exists())
            root.mkdir();
        File gitF = new File("gitme/.git");
        if(!gitF.exists()) {//如果已经初始化过,那肯定有.git文件夹
                        //初始化git库,相当于命令行的 git init
            Git.init().setDirectory(root).call();
        }
        Git git = Git.open(root); //打开git库

                //好吧,随便写一个文件进去先
        File newFile = new File("gitme/"+System.currentTimeMillis()+".java");
        FileWriter fw = new FileWriter(newFile);
        fw.write(System.currentTimeMillis() + " ABC");
        fw.flush();
        fw.close();

                //添加文件咯,相当于 git add .
        git.add().addFilepattern(".+").call();

                //然后当然是提交啦,相当于 git commit
        git.commit().setCommitter("wendal", "wendal1985@gmail.com").setMessage("Try jgit!").call();

        //接下来,我们看看log信息
        for(RevCommit revCommit : git.log().call()){
            System.out.println(revCommit);
            System.out.println(revCommit.getFullMessage());
            System.out.println(revCommit.getCommitterIdent().getName() + " " + revCommit.getCommitterIdent().getEmailAddress());
        }
    }

}

输出的内容:

commit 5fb38fa714f42f5be72cea9221f9264a5944a14e 1310829994 ----sp
Try jgit!
wendal wendal1985@gmail.com

如果你重复运行,会看到好几条哦,呵呵

就现在看来,JGit的API设计得还不错,链式操作,而且比较直观

JGit项目地址: http://www.eclipse.org/jgit



blog comments powered by Disqus

Published

2011-07-16 21:53:35

Categories


Tags

Fork me on GitHub