001/* 002 * Copyright (C) 2015-2021 KeepSafe Software 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package com.getkeepsafe.dexcount.colors; 017 018import org.gradle.api.DefaultTask; 019import org.gradle.api.logging.LogLevel; 020 021import java.io.IOException; 022import java.io.PrintWriter; 023import java.lang.reflect.InvocationTargetException; 024 025public class StyleableTaskAdapter implements Styleable { 026 private final DefaultTask task; 027 028 public StyleableTaskAdapter(DefaultTask task) { 029 this.task = task; 030 } 031 032 @Override 033 public void withStyledOutput(Color color, LogLevel level, IOConsumer<PrintWriter> fn) throws IOException { 034 ServiceRegistryWrapper registry = getServices(); 035 StyledTextOutputFactoryWrapper styledTextOutputFactory = registry.getStyledTextOutputFactory(); 036 StyledTextOutputWrapper baseOutput = styledTextOutputFactory.create("dexcount", level); 037 StyledTextOutputWrapper styledOutput = baseOutput.withStyle(color.getStyle()); 038 try (PrintWriter pw = styledOutput.asPrintWriter()) { 039 fn.accept(pw); 040 } 041 } 042 043 private ServiceRegistryWrapper getServices() { 044 Object registry; 045 try { 046 registry = Reflect.DefaultTask_getServices.invoke(task); 047 } catch (IllegalAccessException | InvocationTargetException e) { 048 throw new RuntimeException(e); 049 } 050 051 return new ServiceRegistryWrapper(registry); 052 } 053}