在java JGit中,如何从远程存储库中删除除最近的提交之外的所有提交

问题描述 投票:0回答:1

我在我的 java 项目上使用 eclipse JGit API 来管理远程 GitHub 存储库,到目前为止我可以使用 JGit 将本地更改提交到远程。但我有这些要求,我只需要保留最近的提交,并且我想丢弃远程存储库中的任何旧提交。

所以我只是好奇是否有一种解决方法可以从远程存储库获取所有提交并一一删除它们。

我已经研究过使用“DeleteBranchCommand”,但删除分支并不一定会删除提交,因为它只删除对提交的引用。

因此,我尝试使用 RevWalk 命令来遍历每个提交,但我找不到删除正在解析的每个提交的命令,以下代码片段取自 https://github.com/centic9/jgit-cookbook 和它用于解析每个提交,但不提供删除提交的方法。

public static void main(String[] args) throws IOException {
     try (Repository repository = CookbookHelper.openJGitCookbookRepository()) {
         Ref head = repository.exactRef("refs/heads/master");

         // a RevWalk allows to walk over commits based on some filtering that is defined
         try (RevWalk walk = new RevWalk(repository)) {
             RevCommit commit = walk.parseCommit(head.getObjectId());
             System.out.println("Start-Commit: " + commit);

             System.out.println("Walking all commits starting at HEAD");
             walk.markStart(commit);
             int count = 0;
             for (RevCommit rev : walk) {
                 System.out.println("Commit: " + rev);
                 //here I want to delete rev
                 count++;
             }
             System.out.println(count);

             walk.dispose();
        }
    }
}
java eclipse github jgit
1个回答
0
投票

我所要做的就是初始化一个新的 git repo 文件夹,在该文件夹中添加所需的文件强制推送到主分支,这只会保留最近的推送。病房后删除 repo 文件夹并每次都执行相同的操作。

FileUtils.deleteDirectory(new File(repoDir+"/new"));
Git git = Git.init().setDirectory(new File(repoDir+"/new")).setInitialBranch("main").call();

git.add().addFilepattern(".").call();
            
RemoteAddCommand remoteAddCommand = git.remoteAdd();
remoteAddCommand.setName("origin");
remoteAddCommand.setUri(new URIish(repoUrl));
remoteAddCommand.call();

git.commit().setMessage("product list "+new Date()).call();

PushCommand pushCommand = git.push();
pushCommand.setCredentialsProvider(credentialsProvider);
pushCommand.setForce(true);
pushCommand.call();
© www.soinside.com 2019 - 2024. All rights reserved.