jGit – 如何将所有文件添加到临时区域
我尝试了很多方法用jGit克隆一个repo(它有效)。 然后,我在存储库中写了一些存档,并尝试添加所有( git add *
, git add -A
或类似的东西)..但它不起作用。 文件简单不会添加到临时区域。
我的代码是这样的:
FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository repository = builder.setGitDir(new File(folder)) .readEnvironment().findGitDir().setup().build(); CloneCommand clone = Git.cloneRepository(); clone.setBare(false).setCloneAllBranches(true); clone.setDirectory(f).setURI("git@192.168.2.43:test.git"); try { clone.call(); } catch (GitAPIException e) { e.printStackTrace(); } Files.write("testing it...", new File(folder + "/test2.txt"), Charsets.UTF_8); Git g = new Git(repository); g.add().addFilepattern("*").call();
我究竟做错了什么? 谢谢。
使用addFilePattern(“。”)尝试时遇到exception:
Exception in thread "main" org.eclipse.jgit.errors.NoWorkTreeException: Bare Repository has neither a working tree, nor an index at org.eclipse.jgit.lib.Repository.getIndexFile(Repository.java:850) at org.eclipse.jgit.dircache.DirCache.lock(DirCache.java:264) at org.eclipse.jgit.lib.Repository.lockDirCache(Repository.java:906) at org.eclipse.jgit.api.AddCommand.call(AddCommand.java:138) at net.ciphersec.git.GitTests.main(GitTests.java:110)
调试这个的一个简单方法是查看JGit 仓库中AddCommand的测试: AddCommandTest.java
您将看到,为了添加所有文件,从不使用模式“ *
”,但“ .
”是。
它用于名为… testAddWholeRepo()
(!)的测试函数中
git.add().addFilepattern(".").call();
例外情况:
Exception in thread "main" org.eclipse.jgit.errors.NoWorkTreeException: Bare Repository has neither a working tree, nor an index
非常明确:您需要在非裸仓库中添加文件。
请参阅测试方法testCloneRepository()
以与您自己的克隆进行比较,并查看是否存在任何差异。
我有一种情况,我必须将文件f1从当前目录移动到另一个名为’temp’的目录。 移动文件后,调用git.add()。addFilePattern(“。”)。call()以一种奇怪的方式起作用,因为git status给出了以下结果:
Changes to be committed: (use "git reset HEAD ..." to unstage) new file: temp/f1.html Changes not staged for commit: (use "git add/rm ..." to update what will be committed) (use "git checkout -- ..." to discard changes in working directory) deleted: f1.html
它识别出创建了一个新的文件temp / f1,但没有检测到该文件是否先被删除。 这可能是因为移动文件可以看作如下
- 删除/剪切文件f1
- 创建一个名为temp的文件夹
- 创建/粘贴文件f1
然后我遇到了setUpdate(true)
,它查找已经被跟踪的文件的更新,并且不会setUpdate(true)
新文件。 (查看java-doc了解更多信息)
因此我必须将代码更改为两行,以便让git识别添加和修改的文件(包括删除):
git.add().addFilepattern(".").call(); git.add().setUpdate(true).addFilepattern(".").call();
git status现在给出了预期的结果:
renamed: f1.hml -> temp/f1.html
它可能是通配符,我只是读取了add命令的javadoc,看起来你发送了一个目录的名称,以便添加它的内容而不是外卡:
addFilepattern public AddCommand addFilepattern(String filepattern)
参数: filepattern
– 要添加内容的文件。 还可以给出一个前导目录名(例如,添加dir/file1
和dir/file2
的目录) ,以递归方式添加目录中的所有文件 。 Fileglobs(例如*.c
)尚不支持。