0

My code delete just files which parse to Jenkins name in the file. I would like to delete file based on the author (Jenkins) in the last commit. What is the best solution for that?

def changelogPath = "C:\\test"
def PackID = "test"

def delete(String changelogPath, String PackID) {
    String folderPath = "$changelogPath"+ "\\" + "$PackID"
    new File(folderPath).eachFile(FileType.FILES) { file ->
      if (file.name.contains('Jenkins')) file.delete()
}

delete(changelogPath, PackID)
Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79
John Doe
  • 147
  • 1
  • 1
  • 10
  • check this post - https://stackoverflow.com/questions/23151837/get-file-owner-metadata-information-with-java – Rao Aug 28 '17 at 06:57

1 Answers1

0

In order to find all files that have been changed with a certain commit, you need a diff of that commit with its predecessor.

You can let JGit compute a list of DiffEntries like this:

ObjectReader reader = git.getRepository().newObjectReader();
CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
ObjectId oldTree = git.getRepository().resolve( "HEAD^{tree}" ); 
oldTreeIter.reset( reader, oldTree );
CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
ObjectId newTree = git.getRepository().resolve( "HEAD~1^{tree}" );
newTreeIter.reset( reader, newTree );

DiffFormatter df = new DiffFormatter( new ByteArrayOutputStream() );
df.setRepository( git.getRepository() );
List<DiffEntry> entries = df.scan( oldTreeIter, newTreeIter );

Each DiffEntry has a path that denotes the file which was added, changed, or deleted. The path is relative to the root of the working directory of the repository. Actually, there is an oldPath and newPath, see the JavaDoc which one to use when.

See also here for a general overview of JGit's diff API: http://www.codeaffine.com/2016/06/16/jgit-diff/

Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79
  • There's no easier way ? For example use `class PersonIdent` and `getAuthor` method ? – John Doe Aug 28 '17 at 08:58
  • The author and committer is the same for all changed files in a commit – Rüdiger Herrmann Aug 28 '17 at 09:14
  • If I understand correctly, for me it will work. If author in last commit is Jenkins -> Delete this file. So how use `getAuthor` in if statement to delete ? – John Doe Aug 28 '17 at 09:35
  • 1
    Not sure what relation there is between 'Jenkins' and the file to delete. However, to get the author of a commit, see this question: https://stackoverflow.com/questions/42820282/get-the-latest-commit-in-a-repository-with-jgit. The `RevCommit` hold all the metadata about a commit. – Rüdiger Herrmann Aug 28 '17 at 10:31