Skip to content

Commit

Permalink
Pretty print convenience methods
Browse files Browse the repository at this point in the history
Pretty printing build info mfuerstenau#25
  • Loading branch information
jfcameron committed Jul 7, 2018
1 parent 5df4ced commit c7c8e8d
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 3 deletions.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,17 @@ buildscript {
apply plugin: 'de.fuerstenau.buildconfig' // actually applies the plugin
```

## Pretty printing
The contents of BuildInfo can be printed, either directly to standard out via the method ```prettyPrint();``` or in a user defined way:
```java
de.fuerstenau.BuildInfo.prettyPrint((fields) ->
{
for (final Field field : fields)
System.out.println("Name: " + field.getName());
});
```
This allows one to conveniently render the full set of fields to XML, JSON, or write to a log, etc.

## Compatibility

* Oracle JDK and OpenJDK 1.7 compatible,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,27 @@ class ClassWriter extends Writer

private final Writer delegate
private boolean isClass

private String pkg
private String cls

ClassWriter (Writer delegate)
ClassWriter (Writer delegate, String pkg, String cls)
{
this.delegate = delegate
this.pkg = pkg
this.cls = cls
}

ClassWriter writePackage (String pkg) throws IOException
{
if (isClass)
throw new IllegalStateException ("cannot write package if class is already written")
delegate.write ("package ${pkg};\n\n")
delegate.write ("""package ${pkg};
import java.util.List;
import java.lang.reflect.Field;
""")
this
}

Expand Down Expand Up @@ -98,7 +108,33 @@ class ClassWriter extends Writer
public void close () throws IOException
{
if (isClass)
{
delegate.write(""" public interface PrettyPrinter
{
public void print(Field[] field);
}
public static void prettyPrint(PrettyPrinter printer)
{
printer.print(${pkg}.${cls}.class.getDeclaredFields());
}
public static void prettyPrint()
{
prettyPrint((fields) ->
{
for (final Field field : fields)
try
{
System.out.println(field.getName() + ": " + field.get(null));\n\
}
catch (IllegalArgumentException | IllegalAccessException ex)
{
}
});
}""")
delegate.write ("}\n")
}
delegate.close ()
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ class GenerateBuildConfigTask extends DefaultTask

new ClassWriter (
Files.newBufferedWriter (outputFile, Charset.forName (charset),
StandardOpenOption.CREATE)).withCloseable { w ->
StandardOpenOption.CREATE), packageName, clsName).withCloseable { w ->
w.writePackage (packageName).writeClass (clsName)

mergedClassFields.values ().each { cf ->
Expand Down

0 comments on commit c7c8e8d

Please sign in to comment.