仅在文件更改时提交/记录

时间:2014-06-26 23:36:55

标签: git groovy egit jgit

我正在尝试使用jgit来跟踪和提交文件中的更改,但是如果文件内容实际上没有将其日志记录更改为repo中的实际提交,我会看到使用CommitCommand的奇怪行为。

要重现我的问题,请运行此测试用例代码3次。 第一次按预期提交新文件,但为什么在知道文件相同的情况下记录了其他两个执行文件?

我在这里错过了什么吗?

测试用例输出:

# groovy -cp org.eclipse.jgit-3.4.0.201406110918-r.jar testcase.groovy
Repo Not found, creating it!
Saving String to file: repo\test.txt
Added file(s): 1
reflogs size: 1

# groovy -cp org.eclipse.jgit-3.4.0.201406110918-r.jar testcase.groovy
Saving String to file: repo\test.txt
Added file(s): 1
reflogs size: 2

# groovy -cp org.eclipse.jgit-3.4.0.201406110918-r.jar testcase.groovy
Saving String to file: repo\test.txt
Added file(s): 1
reflogs size: 3

# git log
-------
commit b22c369dfeb225254687cccfbf244459395a716f
Author: TestUser <xx@xx>
Date:   Fri Jun 27 01:05:27 2014 +0200

    CMessage

commit 0d8bb99d80c561e7bbc3504fdd9bc7da99bb82e4
Author: TestUser <xx@xx>
Date:   Fri Jun 27 01:04:13 2014 +0200

    CMessage

commit 2195dfe7d5536c88eb3d4e953967463bb699c9b2
Author: TestUser <xx@xx>
Date:   Fri Jun 27 01:04:10 2014 +0200

    CMessage

测试代码:

import org.eclipse.jgit.*
import org.eclipse.jgit.api.*
import org.eclipse.jgit.errors.*
import org.eclipse.jgit.lib.*
import org.eclipse.jgit.dircache.*
import java.nio.file.*

Git repOpen(Path wDir){
  Git git
  try{
    git = Git.open(wDir.toFile())
  }catch(RepositoryNotFoundException e){
    println "Repo Not found, creating it!"
    git = repCreate(wDir)
  }catch(Exception e){
    println "Error openning Repo: ${e}"
  }
  return git
}
Git repCreate(Path wDir){
  Git git
  try{
    InitCommand initCommand = Git.init()
    initCommand.setDirectory(wDir.toFile())
    git = initCommand.call()

    // Set git repo options
    StoredConfig conf = git.getRepository().getConfig()
    conf.setBoolean("core", null, "autocrlf", true)
    conf.setBoolean("core", null, "filemode", false)
    conf.save()

  }catch(Exception e){
    println "Error creating Repo: ${e}"
  }
  return git
}
void saveStringToFile(Path file, String data){
  println "Saving String to file: ${file}"
  new FileWriter(file.toFile()).withWriter { writer -> writer.write(data) }
}


//  DO THE WORK
String dummyFileContent = "DummyContent:\nLine\nLine2\nLine3"

Path repoPath = Paths.get('repo')
Git g = repOpen(repoPath)

Path file = repoPath.resolve(Paths.get('test.txt'))
saveStringToFile(file, dummyFileContent)

DirCache dc = g.add().addFilepattern('.').call()
println "Added file(s): $dc.entryCount"

g.commit().setAll(true).setMessage('CMessage').call()
println "reflogs size: ${g.reflog().call().size()}"

1 个答案:

答案 0 :(得分:2)

调用CommitCommand将始终创建提交,无论是否有任何更改。在您的情况下,第二次和第三次提交将为空,即它不引用任何文件。

要仅在工作目录包含更改时创建提交,您可以首先检查其状态

if( !g.status().call().isClean() ) {
  g.commit()...
}