Skip to content

Instantly share code, notes, and snippets.

@turboBasic
Last active August 16, 2021 22:21
Show Gist options
  • Save turboBasic/6185a30654ae46b1b2e92217831c118e to your computer and use it in GitHub Desktop.
Save turboBasic/6185a30654ae46b1b2e92217831c118e to your computer and use it in GitHub Desktop.
class Inspect for inspecting big objects in Groovy #groovy
import groovy.json.JsonGenerator
import groovy.json.JsonOutput
/**
* Inspects big objects
* Usage:
* println Inspect.unwrapAsJsonWithProperties(sourceSets, 3)
* println Inspect.unwrapAsJsonWithProperties(sourceSets.main.allSource, 2, 150)
* println Inspect.unwrapAsJson(sourceSets.main, 2, 120)
*/
class Inspect {
static String unwrapAsJsonWithProperties(Object o, int depth = 1, int maxValueLength = -1) {
JsonOutput.prettyPrint(
getGenerator(depth, maxValueLength).toJson([
class: o.getClass().getCanonicalName(),
properties: unwrap(
o.properties.findAll { it.key != 'class' },
depth - 1,
maxValueLength
),
])
)
}
static String unwrapAsJson(Object o, int depth = 1, int maxValueLength = -1) {
JsonOutput.prettyPrint(
getGenerator(depth, maxValueLength)
.toJson(
unwrap(
[class: o.getClass().getCanonicalName()] + o.properties.findAll { it.key != 'class' },
depth - 1,
maxValueLength
)
)
)
}
static JsonGenerator getGenerator(int depth = 0, int maxValueLength = -1) {
new JsonGenerator.Options()
.excludeFieldsByName(
'asDynamicObject',
'collectionSchema',
'convention',
'conventionMapping',
'elements',
'elementsAsDynamicObject',
'eventRegister',
'extensions',
'filter',
'instantiator',
'mutationGuard',
'outputDir',
'publicType',
'store',
'type',
)
.addConverter(Object) { Object o ->
unwrap(o, depth, maxValueLength)
}
.build()
}
static Object unwrap(Object o, int depth = 0, int maxValueLength = -1) {
if (o == null) {
return o
}
if ([Number, String, GString].any { o in it }) {
return o.toString().take(maxValueLength < 0 ? Integer.MAX_VALUE : maxValueLength)
}
if (o in List || o.getClass().isArray()) {
if (depth <= 0) {
return "(${o.getClass().getCanonicalName()}) $o".take(maxValueLength < 0 ? Integer.MAX_VALUE : maxValueLength)
}
return o.collect {
unwrap(it, depth-1, maxValueLength)
}
}
if (o in Map) {
true
} else if (o.properties) {
o = [class: o.getClass().toString(), properties: unwrap(o.properties.findAll{ it.key != 'class' }, depth, maxValueLength)]
} else {
return o
}
if (depth <= 0) {
return o.toMapString().take(maxValueLength < 0 ? Integer.MAX_VALUE : maxValueLength)
}
return o.collect { k, v ->
[(k): unwrap(v, depth-1, maxValueLength)]
}
.collectEntries()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment