Line data Source code
1 : // Copyright (C) 2017 The Android Open Source Project 2 : // 3 : // Licensed under the Apache License, Version 2.0 (the "License"); 4 : // you may not use this file except in compliance with the License. 5 : // You may obtain a copy of the License at 6 : // 7 : // http://www.apache.org/licenses/LICENSE-2.0 8 : // 9 : // Unless required by applicable law or agreed to in writing, software 10 : // distributed under the License is distributed on an "AS IS" BASIS, 11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 : // See the License for the specific language governing permissions and 13 : // limitations under the License. 14 : 15 : package com.google.gerrit.server.edit.tree; 16 : 17 : import com.google.common.collect.ImmutableList; 18 : import com.google.common.collect.ImmutableSet; 19 : import java.io.IOException; 20 : import java.util.List; 21 : import org.eclipse.jgit.dircache.DirCacheEditor; 22 : import org.eclipse.jgit.lib.ObjectId; 23 : import org.eclipse.jgit.lib.Repository; 24 : import org.eclipse.jgit.revwalk.RevWalk; 25 : import org.eclipse.jgit.treewalk.TreeWalk; 26 : 27 : /** A {@code TreeModification} which renames a file or moves it to a different path. */ 28 : public class RenameFileModification implements TreeModification { 29 : 30 : private final String currentFilePath; 31 : private final String newFilePath; 32 : 33 8 : public RenameFileModification(String currentFilePath, String newFilePath) { 34 8 : this.currentFilePath = currentFilePath; 35 8 : this.newFilePath = newFilePath; 36 8 : } 37 : 38 : @Override 39 : public List<DirCacheEditor.PathEdit> getPathEdits( 40 : Repository repository, ObjectId treeId, ImmutableList<? extends ObjectId> parents) 41 : throws IOException { 42 8 : if (ObjectId.zeroId().equals(treeId)) { 43 1 : return ImmutableList.of(); 44 : } 45 : 46 7 : try (RevWalk revWalk = new RevWalk(repository)) { 47 7 : try (TreeWalk treeWalk = 48 7 : TreeWalk.forPath(revWalk.getObjectReader(), currentFilePath, treeId)) { 49 7 : if (treeWalk == null) { 50 0 : return ImmutableList.of(); 51 : } 52 7 : DirCacheEditor.DeletePath deletePathEdit = new DirCacheEditor.DeletePath(currentFilePath); 53 7 : AddPath addPathEdit = 54 7 : new AddPath(newFilePath, treeWalk.getFileMode(0), treeWalk.getObjectId(0)); 55 7 : return ImmutableList.of(deletePathEdit, addPathEdit); 56 0 : } 57 0 : } 58 : } 59 : 60 : @Override 61 : public ImmutableSet<String> getFilePaths() { 62 8 : return ImmutableSet.of(currentFilePath, newFilePath); 63 : } 64 : }