code-assert icon indicating copy to clipboard operation
code-assert copied to clipboard

Document additional use-cases

Open axelfontaine opened this issue 4 years ago • 1 comments

This library is a real gem and very powerful. The DSL is very easy to read, however it isn't very discoverable when being used for the first time. This is no doubt hurting adoption quite a bit.

I had to search and experiment quite a long time to figure out how to restrict dependencies between certain packages in my code and certain external libraries. After a lot of NPEs and digging through the tests of this project on GitHub, I eventually came up with this:

class ComMyProject : DependencyRuler() {
    var p1: DependencyRule? = null
    var p2: DependencyRule? = null
    var p3: DependencyRule? = null
    override fun defineRules() {
        base().mayUse(base().allSubOf())
        p1?.mayUse(p2)
        p2?.mayUse(p3)
    }
}

val comMyProject = ComMyProject()
val rules = DependencyRules.denyAll()
    .withRelativeRules(comVeturantoServer)
    .withExternals(
        // Unrestricted use of these external packages
        "java.*",
        "javax.*",
        "org.*",
        "net.*",
        "kotlin.*",
        "kotlinx.*"
    )
allow(rules, comMyProject.p2, "com.mapbox.*")
allow(rules, comMyProject.p3, "com.google.gson")

assertThat(DependencyAnalyzer(config).rules(rules).analyze(), matchesRulesExactly())
private fun allow(
    rules: DependencyRules,
    rule: DependencyRule?,
    pkg: String
) {
    rules.addRule(
        rules.rule(
            pkg
        ).mayBeUsedBy(
            rule
        )
    )
}

This took me over an hour and, while it works, I still have no idea whether this is the idiomatic way to do this.

Adding a few more examples to the docs for this case and a number of other common ones would be immensely helpful.

axelfontaine avatar Nov 24 '20 08:11 axelfontaine

I like! I also had to experiment a while for that. @axelfontaine, make a PR :)

Stefku avatar Oct 12 '23 11:10 Stefku