有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java jGit如何将所有文件添加到临时区域

我尝试了很多方法用jGit克隆回购协议(它很管用)。 然后,我在存储库中编写了一些归档文件,并尝试添加所有(a 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 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)

共 (3) 个答案

  1. # 1 楼答案

    我遇到过这样一种情况:我必须将文件f1从当前目录移动到另一个名为“temp”的目录。移动文件后,调用git。添加()。addFilePattern(“.”)。call()的行为很奇怪,因为git status给出了以下结果:

    Changes to be committed:
      (use "git reset HEAD <file>..." to unstage)
    
        new file:   temp/f1.html
    
    Changes not staged for commit:
      (use "git add/rm <file>..." to update what will be committed)
      (use "git checkout   <file>..." to discard changes in working directory)
    
        deleted:    f1.html
    

    它识别出创建了一个新文件temp/f1,但没有检测到该文件首先被删除。这可能是因为移动文件可以如下所示

    • 删除/剪切文件f1
    • 创建一个名为temp的文件夹
    • 创建/粘贴文件f1

    然后我遇到了setUpdate(true),它会查找已被跟踪的文件的更新,并且不会发布新文件。(查看java文档了解更多信息)

    所以我不得不将代码改为两行,这样git才能识别添加和修改的文件(包括删除):

    git.add().addFilepattern(".").call();
    git.add().setUpdate(true).addFilepattern(".").call();
    

    git status现在给出了预期结果:

    renamed:    f1.hml -> temp/f1.html
    
  2. # 2 楼答案

    可能是通配符,我刚刚阅读了add命令的javadoc,看起来您发送目录名是为了添加其内容,而不是通配符:

    addFilepattern
    
    public AddCommand addFilepattern(String filepattern)
    

    参数:filepattern-要从中添加内容的文件也是领先的目录 可以指定名称(例如添加dir/file1dir/file2的目录)来添加所有 目录中的文件,以递归方式Fileglobs(例如*.c)还没有更新 支持

  3. # 3 楼答案

    调试它的一个简单方法是查看JGit repo:^{}AddCommand的测试

    您将看到,为了添加所有文件,从不使用模式“*”,而是使用“.
    它被用于名为^{}(!)

    git.add().addFilepattern(".").call();
    

    例外情况:

    Exception in thread "main" org.eclipse.jgit.errors.NoWorkTreeException: 
    Bare Repository has neither a working tree, nor an index
    

    非常明确:您需要在非裸回购中添加文件

    请参阅test method ^{}以与您自己的克隆进行比较,并查看是否有任何差异