001/* 002 * JDrupes Builder 003 * Copyright (C) 2025 Michael N. Lipp 004 * 005 * This program is free software: you can redistribute it and/or modify 006 * it under the terms of the GNU Affero General Public License as 007 * published by the Free Software Foundation, either version 3 of the 008 * License, or (at your option) any later version. 009 * 010 * This program is distributed in the hope that it will be useful, 011 * but WITHOUT ANY WARRANTY; without even the implied warranty of 012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 013 * GNU Affero General Public License for more details. 014 * 015 * You should have received a copy of the GNU Affero General Public License 016 * along with this program. If not, see <https://www.gnu.org/licenses/>. 017 */ 018 019package org.jdrupes.builder.core; 020 021import com.google.common.flogger.FluentLogger; 022import java.io.IOException; 023import java.nio.file.Files; 024import java.nio.file.Path; 025import org.jdrupes.builder.api.Cleanliness; 026import org.jdrupes.builder.api.Generator; 027import org.jdrupes.builder.api.Project; 028import org.jdrupes.builder.api.Renamable; 029import org.jdrupes.builder.api.ResourceRequest; 030import static org.jdrupes.builder.api.ResourceType.CleanlinessType; 031 032/// A base implementation of a [Generator]. 033/// 034public abstract class AbstractGenerator extends AbstractProvider 035 implements Generator, Renamable { 036 037 private static final FluentLogger logger = FluentLogger.forEnclosingClass(); 038 private final Project project; 039 040 /// Instantiates a new abstract generator. 041 /// 042 /// @param project the project 043 /// 044 public AbstractGenerator(Project project) { 045 this.project = project; 046 } 047 048 @Override 049 public final Project project() { 050 return project; 051 } 052 053 @Override 054 public AbstractGenerator name(String name) { 055 rename(name); 056 return this; 057 } 058 059 /// If the request includes [Cleanliness] deletes the given files 060 /// and returns `true`. 061 /// 062 /// @param requested the requested resource 063 /// @param files the files 064 /// @return true, if successful 065 /// 066 protected boolean cleanup(ResourceRequest<?> requested, Path... files) { 067 if (!requested.accepts(CleanlinessType)) { 068 return false; 069 } 070 for (Path file : files) { 071 try { 072 Files.deleteIfExists(file); 073 } catch (IOException e) { 074 logger.atWarning().log("%s cannot be deleted.", file); 075 } 076 } 077 return true; 078 } 079 080 @Override 081 public String toString() { 082 return super.toString() + "[" + project().nameWithDirectory() + "]"; 083 } 084 085}