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.Collections; 21 : import java.util.List; 22 : import org.eclipse.jgit.dircache.DirCacheEditor; 23 : import org.eclipse.jgit.lib.ObjectId; 24 : import org.eclipse.jgit.lib.Repository; 25 : import org.eclipse.jgit.revwalk.RevCommit; 26 : import org.eclipse.jgit.revwalk.RevWalk; 27 : import org.eclipse.jgit.treewalk.TreeWalk; 28 : 29 : /** 30 : * A {@code TreeModification} which restores a file. The file is added again if it was present 31 : * before the specified commit or deleted if it was absent. 32 : */ 33 : public class RestoreFileModification implements TreeModification { 34 : 35 : private final String filePath; 36 : 37 2 : public RestoreFileModification(String filePath) { 38 2 : this.filePath = filePath; 39 2 : } 40 : 41 : @Override 42 : public List<DirCacheEditor.PathEdit> getPathEdits( 43 : Repository repository, ObjectId treeId, ImmutableList<? extends ObjectId> parents) 44 : throws IOException { 45 2 : if (parents.isEmpty()) { 46 1 : DirCacheEditor.DeletePath deletePath = new DirCacheEditor.DeletePath(filePath); 47 1 : return Collections.singletonList(deletePath); 48 : } 49 : 50 1 : try (RevWalk revWalk = new RevWalk(repository)) { 51 1 : RevCommit base = revWalk.parseCommit(parents.get(0)); 52 1 : try (TreeWalk treeWalk = 53 1 : TreeWalk.forPath(revWalk.getObjectReader(), filePath, base.getTree())) { 54 1 : if (treeWalk == null) { 55 0 : DirCacheEditor.DeletePath deletePath = new DirCacheEditor.DeletePath(filePath); 56 0 : return Collections.singletonList(deletePath); 57 : } 58 : 59 1 : AddPath addPath = new AddPath(filePath, treeWalk.getFileMode(0), treeWalk.getObjectId(0)); 60 1 : return Collections.singletonList(addPath); 61 0 : } 62 0 : } 63 : } 64 : 65 : @Override 66 : public ImmutableSet<String> getFilePaths() { 67 2 : return ImmutableSet.of(filePath); 68 : } 69 : }