summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/bukkit/plugin/java/annotation/PluginAnnotationProcessor.java
blob: 2f0f8d7fb235accbc94097e80d719c0ad7863739 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
package org.bukkit.plugin.java.annotation;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.bukkit.command.CommandExecutor;
import org.bukkit.permissions.PermissionDefault;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.java.annotation.command.Command;
import org.bukkit.plugin.java.annotation.command.Commands;
import org.bukkit.plugin.java.annotation.dependency.Dependency;
import org.bukkit.plugin.java.annotation.dependency.LoadBefore;
import org.bukkit.plugin.java.annotation.dependency.SoftDependency;
import org.bukkit.plugin.java.annotation.permission.ChildPermission;
import org.bukkit.plugin.java.annotation.permission.Permission;
import org.bukkit.plugin.java.annotation.permission.Permissions;
import org.bukkit.plugin.java.annotation.plugin.ApiVersion;
import org.bukkit.plugin.java.annotation.plugin.Description;
import org.bukkit.plugin.java.annotation.plugin.LoadOrder;
import org.bukkit.plugin.java.annotation.plugin.LogPrefix;
import org.bukkit.plugin.java.annotation.plugin.Plugin;
import org.bukkit.plugin.java.annotation.plugin.Website;
import org.bukkit.plugin.java.annotation.plugin.author.Author;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.nodes.Tag;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror;
import javax.tools.Diagnostic;
import javax.tools.FileObject;
import javax.tools.StandardLocation;
import java.io.IOException;
import java.io.Writer;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

@SupportedAnnotationTypes( "org.bukkit.plugin.java.annotation.*" )
@SupportedSourceVersion( SourceVersion.RELEASE_8 )
public class PluginAnnotationProcessor extends AbstractProcessor {

    private boolean hasMainBeenFound = false;

    private static final DateTimeFormatter dFormat = DateTimeFormatter.ofPattern( "yyyy/MM/dd HH:mm:ss", Locale.ENGLISH );

    @Override
    public boolean process(Set<? extends TypeElement> annots, RoundEnvironment rEnv) {
        Element mainPluginElement = null;
        hasMainBeenFound = false;

        Set<? extends Element> elements = rEnv.getElementsAnnotatedWith( Plugin.class );
        if ( elements.size() > 1 ) {
            raiseError( "Found more than one plugin main class" );
            return false;
        }

        if ( elements.isEmpty() ) {
            return false;
        }
        if ( hasMainBeenFound ) {
            raiseError( "The plugin class has already been located, aborting!" );
            return false;
        }
        mainPluginElement = elements.iterator().next();
        hasMainBeenFound = true;

        TypeElement mainPluginType;
        if ( mainPluginElement instanceof TypeElement ) {
            mainPluginType = ( TypeElement ) mainPluginElement;
        } else {
            raiseError( "Element annotated with @Plugin is not a type!", mainPluginElement );
            return false;
        }

        if ( !( mainPluginType.getEnclosingElement() instanceof PackageElement ) && !mainPluginType.getModifiers().contains( Modifier.STATIC ) ) {
            raiseError( "Element annotated with @Plugin is not top-level or static nested!", mainPluginType );
            return false;
        }

        if ( !processingEnv.getTypeUtils().isSubtype( mainPluginType.asType(), fromClass( JavaPlugin.class ) ) ) {
            raiseError( "Class annotated with @Plugin is not an subclass of JavaPlugin!", mainPluginType );
        }

        Map<String, Object> yml = Maps.newLinkedHashMap(); // linked so we can maintain the same output into file for sanity

        // populate mainName
        final String mainName = mainPluginType.getQualifiedName().toString();
        yml.put( "main", mainName ); // always override this so we make sure the main class name is correct

        // populate plugin name
        processAndPut( yml, "name", mainPluginType, mainName.substring( mainName.lastIndexOf( '.' ) + 1 ), Plugin.class, String.class, "name" );

        // populate version
        processAndPut( yml, "version", mainPluginType, Plugin.DEFAULT_VERSION, Plugin.class, String.class, "version" );

        // populate plugin description
        processAndPut( yml, "description", mainPluginType, null, Description.class, String.class );

        // populate plugin load order
        processAndPut( yml, "load", mainPluginType, null, LoadOrder.class, String.class );

        // authors
        Author[] authors = mainPluginType.getAnnotationsByType( Author.class );
        List<String> authorMap = Lists.newArrayList();
        for ( Author auth : authors ) {
            authorMap.add( auth.value() );
        }
        if ( authorMap.size() > 1 ) {
            yml.put( "authors", authorMap );
        } else if ( authorMap.size() == 1 ) {
            yml.put( "author", authorMap.iterator().next() );
        }

        // website
        processAndPut( yml, "website", mainPluginType, null, Website.class, String.class );

        // prefix
        processAndPut( yml, "prefix", mainPluginType, null, LogPrefix.class, String.class );

        // dependencies
        Dependency[] dependencies = mainPluginType.getAnnotationsByType( Dependency.class );
        List<String> hardDependencies = Lists.newArrayList();
        for ( Dependency dep : dependencies ) {
            hardDependencies.add( dep.value() );
        }
        if ( !hardDependencies.isEmpty() ) yml.put( "depend", hardDependencies );

        // soft-dependencies
        SoftDependency[] softDependencies = mainPluginType.getAnnotationsByType( SoftDependency.class );
        String[] softDepArr = new String[ softDependencies.length ];
        for ( int i = 0; i < softDependencies.length; i++ ) {
            softDepArr[ i ] = softDependencies[ i ].value();
        }
        if ( softDepArr.length > 0 ) yml.put( "softdepend", softDepArr );

        // load-before
        LoadBefore[] loadBefore = mainPluginType.getAnnotationsByType( LoadBefore.class );
        String[] loadBeforeArr = new String[ loadBefore.length ];
        for ( int i = 0; i < loadBefore.length; i++ ) {
            loadBeforeArr[ i ] = loadBefore[ i ].value();
        }
        if ( loadBeforeArr.length > 0 ) yml.put( "loadbefore", loadBeforeArr );

        // commands
        // Begin processing external command annotations
        Map<String, Map<String, Object>> commandMap = Maps.newLinkedHashMap();
        boolean result = processExternalCommands( rEnv.getElementsAnnotatedWith( Command.class ), mainPluginType, commandMap );
        if ( !result ) {
            // #processExternalCommand already raised the errors
            return false;
        }

        Commands commands = mainPluginType.getAnnotation( Commands.class );

        // Check main class for any command annotations
        if ( commands != null ) {
            Map<String, Map<String, Object>> merged = Maps.newLinkedHashMap();
            merged.putAll( commandMap );
            merged.putAll( this.processCommands( commands ) );
            commandMap = merged;
        }

        yml.put( "commands", commandMap );

        // Permissions
        Map<String, Map<String, Object>> permissionMetadata = Maps.newLinkedHashMap();

        Set<? extends Element> permissionAnnotations = rEnv.getElementsAnnotatedWith( Command.class );
        if ( permissionAnnotations.size() > 0 ) {
            for ( Element element : permissionAnnotations ) {
                if ( element.equals( mainPluginElement ) ) {
                    continue;
                }
                if ( element.getAnnotation( Permission.class ) != null ) {
                    Permission permissionAnnotation = element.getAnnotation( Permission.class );
                    permissionMetadata.put( permissionAnnotation.name(), this.processPermission( permissionAnnotation ) );
                }
            }
        }

        Permissions permissions = mainPluginType.getAnnotation( Permissions.class );
        if ( permissions != null ) {
            Map<String, Map<String, Object>> joined = Maps.newLinkedHashMap();
            joined.putAll( permissionMetadata );
            joined.putAll( this.processPermissions( permissions ) );
            permissionMetadata = joined;
        }
        yml.put( "permissions", permissionMetadata );

        // api-version
        if ( mainPluginType.getAnnotation( ApiVersion.class ) != null ) {
            ApiVersion apiVersion = mainPluginType.getAnnotation( ApiVersion.class );
            if ( apiVersion.value() != ApiVersion.Target.DEFAULT ) {
                yml.put( "api-version", apiVersion.value().getVersion() );
            }
        }

        try {
            Yaml yaml = new Yaml();
            FileObject file = this.processingEnv.getFiler().createResource( StandardLocation.CLASS_OUTPUT, "", "plugin.yml" );
            try ( Writer w = file.openWriter() ) {
                w.append( "# Auto-generated plugin.yml, generated at " )
                 .append( LocalDateTime.now().format( dFormat ) )
                 .append( " by " )
                 .append( this.getClass().getName() )
                 .append( "\n\n" );
                // have to format the yaml explicitly because otherwise it dumps child nodes as maps within braces.
                String raw = yaml.dumpAs( yml, Tag.MAP, DumperOptions.FlowStyle.BLOCK );
                w.write( raw );
                w.flush();
                w.close();
            }
            // try with resources will close the Writer since it implements Closeable
        } catch ( IOException e ) {
            throw new RuntimeException( e );
        }

        processingEnv.getMessager().printMessage( Diagnostic.Kind.WARNING, "NOTE: You are using org.bukkit.plugin.java.annotation, an experimental API!" );
        return true;
    }

    private void raiseError(String message) {
        this.processingEnv.getMessager().printMessage( Diagnostic.Kind.ERROR, message );
    }

    private void raiseError(String message, Element element) {
        this.processingEnv.getMessager().printMessage( Diagnostic.Kind.ERROR, message, element );
    }

    private TypeMirror fromClass(Class<?> clazz) {
        return processingEnv.getElementUtils().getTypeElement( clazz.getName() ).asType();
    }

    private <A extends Annotation, R> R processAndPut(
            Map<String, Object> map, String name, Element el, R defaultVal, Class<A> annotationType, Class<R> returnType) {
        return processAndPut( map, name, el, defaultVal, annotationType, returnType, "value" );
    }

    private <A extends Annotation, R> R processAndPut(
            Map<String, Object> map, String name, Element el, R defaultVal, Class<A> annotationType, Class<R> returnType, String methodName) {
        R result = process( el, defaultVal, annotationType, returnType, methodName );
        if ( result != null )
            map.put( name, result );
        return result;
    }

    private <A extends Annotation, R> R process(Element el, R defaultVal, Class<A> annotationType, Class<R> returnType, String methodName) {
        R result;
        A ann = el.getAnnotation( annotationType );
        if ( ann == null ) result = defaultVal;
        else {
            try {
                Method value = annotationType.getMethod( methodName );
                Object res = value.invoke( ann );
                result = ( R ) ( returnType == String.class ? res.toString() : returnType.cast( res ) );
            } catch ( Exception e ) {
                throw new RuntimeException( e ); // shouldn't happen in theory (blame Choco if it does)
            }
        }
        return result;
    }

    private boolean processExternalCommands(Set<? extends Element> commandExecutors, TypeElement mainPluginType, Map<String, Map<String, Object>> commandMetadata) {
        for ( Element element : commandExecutors ) {
            // Check to see if someone annotated a non-class with this
            if ( !( element instanceof TypeElement ) ) {
                this.raiseError( "Specified Command Executor class is not a class." );
                return false;
            }

            TypeElement typeElement = ( TypeElement ) element;
            if ( typeElement.equals( mainPluginType ) ) {
                continue;
            }

            // Check to see if annotated class is actuall a command executor
            TypeMirror mirror = this.processingEnv.getElementUtils().getTypeElement( CommandExecutor.class.getName() ).asType();
            if ( !( this.processingEnv.getTypeUtils().isAssignable( typeElement.asType(), mirror ) ) ) {
                this.raiseError( "Specified Command Executor class is not assignable from CommandExecutor " );
                return false;
            }

            Command annotation = typeElement.getAnnotation( Command.class );
            commandMetadata.put( annotation.name(), this.processCommand( annotation ) );
        }
        return true;
    }

    /**
     * Processes a set of commands.
     *
     * @param commands The annotation.
     *
     * @return The generated command metadata.
     */
    protected Map<String, Map<String, Object>> processCommands(Commands commands) {
        Map<String, Map<String, Object>> commandList = Maps.newLinkedHashMap();
        for ( Command command : commands.value() ) {
            commandList.put( command.name(), this.processCommand( command ) );
        }
        return commandList;
    }

    /**
     * Processes a single command.
     *
     * @param commandAnnotation The annotation.
     *
     * @return The generated command metadata.
     */
    protected Map<String, Object> processCommand(Command commandAnnotation) {
        Map<String, Object> command = Maps.newLinkedHashMap();

        if ( commandAnnotation.aliases().length == 1 ) {
            command.put( "aliases", commandAnnotation.aliases()[ 0 ] );
        } else if ( commandAnnotation.aliases().length > 1 ) {
            command.put( "aliases", commandAnnotation.aliases() );
        }

        if ( !"".equals( commandAnnotation.desc() ) ) {
            command.put( "description", commandAnnotation.desc() );
        }
        if ( !"".equals( commandAnnotation.permission() ) ) {
            command.put( "permission", commandAnnotation.permission() );
        }
        if ( !"".equals( commandAnnotation.permissionMessage() ) ) {
            command.put( "permission-message", commandAnnotation.permissionMessage() );
        }
        if ( !"".equals( commandAnnotation.usage() ) ) {
            command.put( "usage", commandAnnotation.usage() );
        }

        return command;
    }

    /**
     * Processes a command.
     *
     * @param permissionAnnotation The annotation.
     *
     * @return The generated permission metadata.
     */
    protected Map<String, Object> processPermission(Permission permissionAnnotation) {
        Map<String, Object> permission = Maps.newLinkedHashMap();

        if ( !"".equals( permissionAnnotation.desc() ) ) {
            permission.put( "description", permissionAnnotation.desc() );
        }
        if ( PermissionDefault.OP != permissionAnnotation.defaultValue() ) {
            permission.put( "default", permissionAnnotation.defaultValue().toString().toLowerCase() );
        }

        if ( permissionAnnotation.children().length > 0 ) {
            Map<String, Boolean> childrenList = Maps.newLinkedHashMap(); // maintain order
            for ( ChildPermission childPermission : permissionAnnotation.children() ) {
                childrenList.put( childPermission.name(), childPermission.inherit() );
            }
            permission.put( "children", childrenList );
        }

        return permission;
    }

    /**
     * Processes a set of permissions.
     *
     * @param permissions The annotation.
     *
     * @return The generated permission metadata.
     */
    protected Map<String, Map<String, Object>> processPermissions(Permissions permissions) {
        Map<String, Map<String, Object>> permissionList = Maps.newLinkedHashMap();
        for ( Permission permission : permissions.value() ) {
            permissionList.put( permission.name(), this.processPermission( permission ) );
        }
        return permissionList;
    }
}