javaeclipsegithubjgit

In java JGit, How to remove all commits from remote repository except the most recent one


I am using eclipse JGit API on my java project to mange remote GitHub repository and so far I can use JGit to commit local changes to remote. But I have these requirements that I will only need to keep the most recent commit and I want to discard any old commits from the remote repository.

So I am just curious if there is a workaround to fetch all the commits from remote repo and delete them one by one.

I have looked into using 'DeleteBranchCommand' but deleting a branch does not necessarily remove commits since it only deletes the reference to the commits.

So I tried RevWalk command to walk through each commits, but I could not find a command to remove each commit I am parsing, The following code snippets is taken from https://github.com/centic9/jgit-cookbook and it is used to parse each commits but does not provide the method to remove the commit.

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();
        }
    }
}

Solution

  • All I had to do was init a new git repo folder, add required files in this folder force push to main branch , and this only keeps the recent pushes only. after ward remove the repo folder and do the same every time.

    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();