001 /* 002 * Copyright 2010-2013 JetBrains s.r.o. 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 */ 016 017 package com.sampullara.cli; 018 019 import com.intellij.util.containers.ComparatorUtil; 020 import org.jetbrains.annotations.NotNull; 021 022 import java.lang.reflect.Field; 023 024 public class ArgumentUtils { 025 026 private ArgumentUtils() {} 027 028 @NotNull 029 public static <T> String convertArgumentsToString(T arguments, T defaultArguments) { 030 StringBuilder result = new StringBuilder(); 031 convertArgumentsToString(arguments, defaultArguments, arguments.getClass(), result); 032 return result.toString(); 033 } 034 035 public static <T> void convertArgumentsToString(T arguments, T defaultArguments, Class clazz, StringBuilder result) { 036 Class superClazz = clazz.getSuperclass(); 037 if (superClazz != null) { 038 convertArgumentsToString(arguments, defaultArguments, superClazz, result); 039 } 040 041 for (Field field : clazz.getDeclaredFields()) { 042 Argument argument = field.getAnnotation(Argument.class); 043 if (argument == null) continue; 044 045 Object value; 046 Object defaultValue; 047 try { 048 value = field.get(arguments); 049 defaultValue = field.get(defaultArguments); 050 } 051 catch (IllegalAccessException ignored) { 052 // skip this field 053 continue; 054 } 055 056 if (ComparatorUtil.equalsNullable(value, defaultValue)) continue; 057 058 String name = Args.getAlias(argument); 059 if (name == null) { 060 name = Args.getName(argument, field); 061 } 062 063 result.append("-").append(name).append(" "); 064 065 Class<?> fieldType = field.getType(); 066 if (fieldType != boolean.class && fieldType != Boolean.class) { 067 result.append(value).append(" "); 068 } 069 } 070 } 071 072 }