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.pgm.init; 16 : 17 : import com.google.common.base.Strings; 18 : import com.google.gerrit.common.Die; 19 : import com.google.gerrit.pgm.init.api.ConsoleUI; 20 : import com.google.gerrit.server.config.SitePaths; 21 : import com.google.inject.Inject; 22 : import com.google.inject.Singleton; 23 : import java.io.IOException; 24 : import java.nio.file.DirectoryStream; 25 : import java.nio.file.Files; 26 : import java.nio.file.Path; 27 : 28 : @Singleton 29 : public class StaleLibraryRemover { 30 : private final ConsoleUI ui; 31 : private final Path lib_dir; 32 : 33 : @Inject 34 15 : StaleLibraryRemover(ConsoleUI ui, SitePaths site) { 35 15 : this.ui = ui; 36 15 : this.lib_dir = site.lib_dir; 37 15 : } 38 : 39 : public void remove(String pattern) { 40 8 : if (!Strings.isNullOrEmpty(pattern)) { 41 8 : DirectoryStream.Filter<Path> filter = 42 0 : entry -> entry.getFileName().toString().matches("^" + pattern + "$"); 43 8 : try (DirectoryStream<Path> paths = Files.newDirectoryStream(lib_dir, filter)) { 44 8 : for (Path p : paths) { 45 0 : String old = p.getFileName().toString(); 46 0 : String bak = "." + old + ".backup"; 47 0 : Path dest = p.resolveSibling(bak); 48 0 : if (Files.exists(dest)) { 49 0 : ui.message("WARNING: not renaming %s to %s: already exists\n", old, bak); 50 0 : continue; 51 : } 52 0 : ui.message("Renaming %s to %s\n", old, bak); 53 : try { 54 0 : Files.move(p, dest); 55 0 : } catch (IOException e) { 56 0 : throw new Die("cannot rename " + old, e); 57 0 : } 58 0 : } 59 0 : } catch (IOException e) { 60 0 : throw new Die("cannot remove stale library versions", e); 61 8 : } 62 : } 63 8 : } 64 : }