repositories {
    jcenter()
}

configurations {
    scm
}

dependencies {
    scm 'org.eclipse.jgit:org.eclipse.jgit:4.9.2.201712150930-r'
    scm 'commons-codec:commons-codec:1.7'
    scm 'some:unresolved:2.5'
}

// tag::walk-task[]
task walkDependencyGraph(type: DependencyGraphWalk) {
    dependsOn configurations.scm
}

class DependencyGraphWalk extends DefaultTask {
    @TaskAction
    void walk() {
        Configuration configuration = project.configurations.scm
        ResolutionResult resolutionResult = configuration.incoming.resolutionResult
        ResolvedComponentResult root = resolutionResult.root
        logger.quiet configuration.name
        traverseDependencies(0, root.dependencies)
    }

    private void traverseDependencies(int level, Set<? extends DependencyResult> results) {
        for (DependencyResult result : results) {
            if (result instanceof ResolvedDependencyResult) {
                ResolvedComponentResult componentResult = result.selected
                ComponentIdentifier componentIdentifier = componentResult.id
                String node = calculateIndentation(level) + "- $componentIdentifier.displayName ($componentResult.selectionReason)"
                logger.quiet node
                traverseDependencies(level + 1, componentResult.dependencies)
            } else if (result instanceof UnresolvedDependencyResult) {
                ComponentSelector componentSelector = result.attempted
                String node = calculateIndentation(level) + "- $componentSelector.displayName (failed)"
                logger.quiet node
            }
        }
    }

    private String calculateIndentation(int level) {
        '     ' * level
    }
}
// end::walk-task[]
